JavaScript Challenge - Semi-Prime Numbers

This community-built FAQ covers the “Semi-Prime Numbers” code challenge in JavaScript. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the JavaScript challenge Semi-Prime Numbers

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in Language Help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to Language Help and Tips and Resources. If you are wanting feedback or inspiration for a project, check out Projects.

Looking for motivation to keep learning? Join our wider discussions in Community

Learn more about how to use this guide.

Found a bug? Report it online, or post in Bug Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Solution to the problem-

function checkPrime(n){
  for (let i=2; i<=n/2; i++){
    if(n%i==0){
      return false;
    }
  }
  return true;
}
function checkSemiPrime(number) {
  let divisors=[];
  for (let i = 2; i * i <= number; ++i){
      if (number % i == 0) {
          divisors.push(i);
          if (i != number / i) divisors.push(number / i);
      }
  }
  let isPrime=true;
  if(divisors.length){
    for (let j = 0; j < divisors.length; ++j){
        if(!checkPrime(divisors[j])){
          isPrime=false
          break;
        }
    }
  }
  if(isPrime && divisors.length){
      return true;
    }
  return false;
}
function semiPrimeCount(n) {
  let counter=0;
  for (let i = 4; i < n; ++i){
    if(checkSemiPrime(i)){
      counter++;
    }
  }
  console.log('count',counter)
  return counter;
}
semiPrimeCount(10);
// Leave this so we can test your code:
module.exports = semiPrimeCount;

1 Like

function semiPrimeCount(n) {
let res=;
let doublon=true;
let z=null;
for (let x=2;x<n;x++) {
if(primenumber(x)){
for (let y=2;y<n;y++) {
if(primenumber(y)) {
z=x*y;
doublon=res.some(a => a==z);
if(doublon==false && z < n) res.push(z);
}
}
}
}
return res.length;
}

function primenumber(x){
if(x < 2) return false;
for (let i = 2; i <= Math.sqrt(x); i++) {
if (x % i == 0) return false;
}
return true;
}

semiPrimeCount(10);

// Leave this so we can test your code:
module.exports = semiPrimeCount;

function semiPrimeCount(n) {
  // pArray represents possible prime numbers
  const pArray = [];
    //Get prime Numers and put in pArray
  for (let i=2; i<n; i++) {
    //number to be divided by
    let isPrime = true;
    for (let j=Math.ceil(i/2); j>1; j--) {
      if (i === j) {
        continue;
      } else if (i%j === 0) {
        isPrime = false;
        break;
      }
    }
      if (isPrime) {
        if (!pArray.includes(i)) {
          pArray.push(i);
      }
    }
   }  
  // Calculate and count semiPrimes
  let count = 0;
  let semiPrimes = [];
  for (let x= 4; x<n; x++) {
    //y is index of pArray
    for (let y = 0; y < pArray.length; y++) {
      let semiPrime = false;
      if (!semiPrime) {
        // z is other index of pArray to multiply by y
        for (let z = 0; z<pArray.length; z++) {
    
          if ((pArray[z] * pArray[y] === x) && !semiPrimes.includes(x)) {
            semiPrimes.push(x)
            count++;
            semiPrime = true;
            break;
          }
        }
      }
    }
  }
  console.log(count);
  return count;
}

semiPrimeCount(10);

// Leave this so we can test your code:
module.exports = semiPrimeCount;

function semiPrimeCount(n) {

  let primeList = [];

  for (let num = 2; num <= n; num++) {
    let isPrime = true;

    for (let i = 2; i < num; i++) {
      if (num % i === 0) {
        isPrime = false;
      }
    }
  
    if (isPrime === true) {
      primeList.push(num);
    }
  }

  let semiPrimeList = [];

  for (let j = 0; j < primeList.length; j++) {
    for (let k = 0; k < primeList.length; k++) {
      let semiPrimes = primeList[j] * primeList[k]

      if (semiPrimes < n && !semiPrimeList.includes(semiPrimes)) {
        semiPrimeList.push(semiPrimes)
      }
    }
  }
  console.log(semiPrimeList)
  return semiPrimeList.length;
}

console.log(semiPrimeCount(10));

// Leave this so we can test your code:
module.exports = semiPrimeCount;

function semiPrimeCount(n) {
    const checkIsPrime = (num => {
        for (let i = 2; i < num; i++)
            if (num % i === 0) return false
        return num > 1
    })

    const getPrimeNumbers = (number) => {
        let list = []
        for (let i = 1; i < number; i++) {
            if (checkIsPrime(i)) list.push(i)
        }
        return list
    }

    const nums = getPrimeNumbers(n)
    let result = new Set()
    for (let n1 of nums)
        for (let n2 of nums) {
            const r = n1 * n2
            if (r < n)
                result.add(r)
        }

    return result.size
}

semiPrimeCount(10);

// Leave this so we can test your code:
module.exports = semiPrimeCount;

function semiPrimeCount(n) {
  const primes = [];
  for (var i = 2; i < n/2; i++) {
    if (isPrime(i)) {
      primes.push(i);
    }
  }
  let count = 0;
  for (var i = 0; i < primes.length; i++) {
    for (var j = i; j < primes.length; j++) {
      if (primes[i] * primes[j] < n) {
        count++;
      } else {
        break;
      }
    }
  }
  return count;
}

function isPrime(n) {
  for (var i = 2; i <= n/2; i++) {
    if (n % i === 0) return false;
  }
  return true;
}

// Leave this so we can test your code:
module.exports = semiPrimeCount;

function semiPrimeCount(n) { function primeFinder(n) { let primes = [] for (let i=2; i<= n ; i++){ let count = 0 for (let j=2; j<=i; j++){ if (i%j===0) { count++ } } if (count>1) { count=0 } else { primes.push(i) count=0 } } return primes } let primes = primeFinder(n) let semiPrimes = [] primes.forEach((p,ind,a) => { primes.forEach((e)=>{ if ((p*e<n)&&(!semiPrimes.includes(p*e))) { semiPrimes.push(p*e)} }) }) return semiPrimes.length; } semiPrimeCount(10); // Leave this so we can test your code: module.exports = semiPrimeCount;
function semiPrimeCount(n) {
  let [products,a0,a1,i]=[[],[],[],2]
  while(i<n/2){
    a1.push(i);
    i++;
  }
  a1.forEach(no=>{
    let factors =[];
    let j=1;
    while(j<=no){
    if(no%j===0){factors.push(j)}
    j++;
    }
    if(factors.length===2){a0.push(no);}
  })
  a0.forEach((pri,ind)=>{
    while(ind<a0.length&&pri*a0[ind]<n){
      products.push(pri*a0[ind]);
      ind++;
    }
  });
  return products.length
}
function semiPrimeCount(n) {
  let primeNumbers = [2, 3];
  let semiPrime = [];

  const isPrime = (p) => {
    if(p ===2 && p===3) return true;

    for(let i = 0; i<primeNumbers.length; i++){
      if(p % primeNumbers[i] === 0){
        return false;
      }
    }
    return true;
  }

  const isSemiPrime = (p) => {
    for(let i = 0; i<primeNumbers.length; i++){
      const rem = p % primeNumbers[i];
      const q = p / primeNumbers[i];
      if(rem === 0 && primeNumbers.includes(q)){
        return true;
      }
    }
    return false;
  }

  if(n < 4){
    return [];
  }
  for( let num = 4; num < n; num ++){
    if(isPrime(num)){
      primeNumbers.push(num);
    }else if(isSemiPrime(num)){
      semiPrime.push(num)
    }
  }

  return semiPrime.length;
}

semiPrimeCount(10);

function semiPrimeCount(n) {

const primes =
const semiPrimes =

for(let i=1; i<=n; i++){
if(isPrime(i)){
primes.push(i)
}
}
return isSemiPrime(primes,n)
}

function isSemiPrime(arr, n){
const semiPrimes =
for(let i=1; i<n; i++){
for(let j=0; j < arr.length; j++){
if(i % arr[j] === 0 && i !==arr[j] && isPrime(i / arr[j])){
semiPrimes.push(i)
}
}
}
let uniqueElem = […new Set(semiPrimes)]
return uniqueElem.length
}

function isPrime(num){
if(num === 1){
return false
}

for(let i=2; i<num; i++){
if(num % i === 0){
return false
}
}
return true
}

console.log(semiPrimeCount(10));

// Leave this so we can test your code:
module.exports = semiPrimeCount;

function semiPrimeCount(n) {
  if (n < 3) return 0;
  const primes = [];
  const semiPrimes = new Set();
  label: for (let i = 2; i < n / 2; i++) {
    for (let j = 2; j <= Math.sqrt(i); j++) {
      if (i % j === 0) continue label;
    }
    primes.push(i);
    for (let prime of primes) {
      const mult = prime * i;
      if (mult > n - 1) break;
      semiPrimes.add(mult);
    }
  }
  return semiPrimes.size;
}
[codebyte language=javascript] //javascript practice const createRangeArray = (n) => { let rangeArray = [...Array(n).keys()]; return rangeArray; //WORKING FUNCTION TO CREATE A RANGE ARRAY BASED ON INPUT }; const isItPrime = (num) => { let isPrime = true; if (num <= 1) { isPrime = false; }; //WORKING FUNCTION TO INDETIFY PRIMES for (let i = 2; i < num; i++) { if (num % i === 0) { isPrime = false; break; }; }; return isPrime; }; const createPrimeArray = (n) => { let primeArray = []; for (let i = 0; i <= n; i++) { //WORKING TO CREATE ARRAY OF PRIME NUMBERS if (isItPrime(i) === true) { primeArray.push(i);} } return primeArray; }; const arrayProducts = (array) => { let allProducts = []; for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { //WORKING CORRECTLY TO GIVE allProducts.push(array[i] * array[j]); //A UNIQUE ARRAY OF NUMBERS FROM } //PRODUCTS OF THE INTERNAL ITEMS } allProducts = [...new Set(allProducts)]; return allProducts; }; const compare = (a, b) => { let filteredArray = a.filter(element => b.includes(element)); //COMPARING FOR RESULTS return filteredArray; }; let results = ''; const semiPrimeCount = (n) => { let rangeArray = createRangeArray(n); //FIRST I CREATE THE RANGE ARRAY lines: 3-6 let primeArray = createPrimeArray(n); //THEN CREATE A PRIME ARRAY lines: 8-19 + 21-26 let allProducts = arrayProducts(primeArray) //THEN CREATE AN ARRAY OF SEMIPRIMES lines: 29-37 let filteredArray = compare(rangeArray, allProducts); //THEN COMPARE THE RESULTS lines: 39-42 let results = filteredArray.length; return results; }; console.log(semiPrimeCount(100)); //Leave this so we can test your code: module.exports = semiPrimeCount; [/codebyte]

This is impressive brother. I don’t have a clue how you worked square roots into this but ■■■■. Nice.

1 Like

All factors pairs placed on opposites sides of square root (or equal it both). For example, square root of 12 is 3.46(…). You have factors pairs: 1 * 12, 2 * 6, 3 * 4, 4 * 3, 6 * 2, 12 * 1. One of the factor is less than root and another one is more. Always. And after root they change place. So you need check numbers only from two to square root.

APPLAUSE this is true big brain.

function semiPrimeCount(n) {
  const primeNumbers = [];
    const semiPrimeNumbers = [];
      let check = true;
      let j = 2;
      for (let i = 2; i <= n; i++) {
        while (check && j < i) {
          if (i % j === 0) {
            check = false;
          }
          j++;
        }
        if (check) {
          primeNumbers.push(i);
            primeNumbers.forEach(number => {
              const semiPrimeNumber = number * i;
              if (semiPrimeNumber < n) {
                semiPrimeNumbers.push(semiPrimeNumber);
              }
            });
        }
        check = true;
        j = 2;
        if (primeNumbers[primeNumbers.length -1] * primeNumbers[0] >= n) break;
      }
      return semiPrimeNumbers.length ? semiPrimeNumbers.length : 0;
}

Not as good as @amrakimmerian code, I need to think a bit to understand the square root border, but I still will post my code :slightly_smiling_face: . Almost the same as searching prime numbers only difference is you have to multiply all pairs of prime numbers and if it is lower than n push to a semi-prime list.

1 Like
function semiPrimeCount(n) { let semiCount = 0; let primeNums = []; for (let i = 2; i < n; i++) { let isPrime = true; for (let j = 2; j < i; j++) { if (i % j === 0) { isPrime = false; break; } } if (isPrime) { primeNums.push(i) } } for (let k = 0; k < primeNums.length; k++) { for (let l = k; l < primeNums.length; l++) { if (primeNums[k] * primeNums[l] < n ) { semiCount++; } } } return semiCount; } console.log(semiPrimeCount(10)); // Leave this so we can test your code: module.exports = semiPrimeCount;

I was being lazy.
I used the primeFinder function from the Prime Number Finder challenge to get prime numbers.
Then, to determine whether each number x was semi-prime,
I checked whether any of the prime numbers was a factor of x, and if it was, whether the quotient of x divided by that prime number was in the array of prime numbers.

function semiPrimeCount(n) {
  const maxFactor = Math.floor(n / 2);
  const primes = primeFinder(maxFactor);
  //const semiPrimes = [];
  let count = 0;
  for (let x = 4; x < n; x++) {
    const sqrt_ = Math.floor(Math.sqrt(x));
    for (let p of primes) {
      if ((x % p == 0) && primes.includes(x / p)) {
        //semiPrimes.push(x);
        count++;
      }
      if (p >= sqrt_) {
        break; // avoids duplicates
      } 
    }
  }
  return count;
  //console.log(semiPrimes);
  //return semiPrimes.length;
}

I guess it would have run faster if I used a Set instead of an Array for the primes.