JavaScript Challenge - Prime Number Finder

This community-built FAQ covers the “Prime Number Finder” 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 Prime Number Finder

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!

function primeFinder(n) {
  const arr = [];
  for (let i = 2; i <= n;  i++) {
    let isPrime = true;
    let root = Math.floor(Math.sqrt(i));
    for (let j = 2; j <= root; j++) {
      if (i % j === 0) {
        isPrime = false;
        break;
      }
    }
    if (isPrime) {
      arr.push(i);
    }
  }
  return arr;
}

console.log(primeFinder(11))

// Leave this so we can test your code:
module.exports = primeFinder;
4 Likes

Here’s my code!
Let me know what you think of it!

function primeFinder(n) {
  let primeNumbers = [];
  for (let i = 1; i <= n; i++) {
    if (isItPrime(i)) {
      primeNumbers.push(i);
    }
  }
  return primeNumbers;
}

function isItPrime(n) {
  if (n === 1) {
    return false;
  } else if (n === 2) {
    return true;
  }
  for (let i = n - 1; i > 1; i--) {
    if (n % i === 0) {
      return false;
    }  
  }
  return true;
}

console.log(primeFinder(11))

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

Hey, this is my code. I tried separating my code into reusable chunks. Please let me know what you think about this code

const getFactors = function(number){ const factors = []; for(let count = 1; count <= number/2; count++){ if(number%count === 0){ factors.push(count); } } factors.push(number); return factors; } const isPrime = function(number){ const factors = getFactors(number); return factors.length <= 2 ? true : false } function primeFinder(n) { const primes = []; for(let count = 2; count <= n; count++){ if(isPrime(count)){ primes.push(count) } } return primes } console.log(primeFinder(11)) // Leave this so we can test your code: module.exports = primeFinder;

I’m not a big fan of nested loops, too much room for confusion - but here it is anyways

function primeFinder(n) { // Write your code here let result = [] for(let i = 1; i <= n; i++) { let count = 0 for(let j = 2; j <= i; j++) { if(Number.isInteger(i/j)) { count++ } } if(count === 1) { result.push(i) } } return result } console.log(primeFinder(11)) // Leave this so we can test your code: module.exports = primeFinder;

A naive brute force approach…

function primeFinder(n) {
  const isPrime = function (p) {
    if (p < 2) {
      return false
    }
    if (p > 2) {
      let x = 2
      while (x <= Math.sqrt(p)) {
        if (p % x == 0) {
          return false
        }
        x += x % 2 ? 2 : 1
      }
    }
    return true
  }
  const primes = []
  for (let i = 2; i <= n; i++) {
    if (isPrime(i)) {
      primes.push(i)
    }
  }
  return primes
}

console.log(primeFinder(11))

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

Little bit clumsy but it can be cleaned up on refactor.

It follows that since we are building an array of primes, it could be used in the isPrime() function…

for (let x of primes) {

}

Off to see if that can be done.

Hello,
I am pretty new to JS (around 10 hours). Here is my solution:

function primeFinder(n) { const primes = []; for (let i = 2; i <= n; i++) { primes.push(i); } primes.forEach(element => { const quotient = Math.floor(n / element); for (let j = 2; j <= quotient; j++) { let primeMultiple = j * element; for (let k = 0; k <= primes.length; k++) { if (primeMultiple == primes[k]) { primes.splice(k, 1); } }; } }); return primes; } console.log(primeFinder(100)) // Leave this so we can test your code: module.exports = primeFinder;

Taking a clue from yours, I came up with this, but still have to see if it passes the tests…

const primeFinder = function (n) {
  const primes = [false, false].concat(new Array(n - 1).fill(true));
  const r = Math.floor(Math.sqrt(n) + 1);
  for (let y = 2; y < r; y++) {
    for (let x = 2 * y; x < n; x += y) {
      primes[x] = false;
    }
  }
  primes.forEach((x, i) => {
    if (x) {
      primes[i] = i;
    }
  })
  return primes.filter(x => !! x);
}
console.log(primeFinder(103))

BRB


Had to make a suspected tweak…

const primeFinder = function (n) {
  const primes = [false, false].concat(new Array(n - 1).fill(true));
  const r = Math.floor(Math.sqrt(n) + 1);
  for (let y = 2; y < r; y++) {
    for (let x = 2 * y; x <= n; x += y) {
      primes[x] = false;
    }
  }
  primes.forEach((x, i) => {
    if (x) {
      primes[i] = i;
    }
  })
  return primes.filter(x => !! x);
}
console.log(primeFinder(11))

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

Big-O wise, when we see nested loops it’s automatically N^2 but in this case the first loop is only iterating over the square root of n, and the second is leaping from point to point with lessening frequency. There never truly is an N-squared scenario. Still, worst case. Hmmm.


Interesting thing to note, boolean type uses four bytes, number type uses eight. For anyone wondering if 0 and 1 could be used for brevity.


Shouldn’t be whining; common multiples are getting overwritten steadily. That’s some work.


Also,

Mental logic. This problem doesn’t solve itself. There are edge cases that we as the programmer must consider and explore; at the least, ponder. Toss in the forEach and that makes five mental logic considerations that the code could not solve by itself, things that the intuitive algorithm required to align itself. This is not something we can take lightly. Equip your thinking for this type of case, plus or minus one, etc.

// Return true if n is prime
function isPrime(n) 
{
  if (n < 2) return false;

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

function primeFinder(n) {
 let result = [];
 for (let i = 0; i <= n; i++) {
   if (isPrime(i)) result.push(i)
 }
 return result;
}

console.log(primeFinder(11))

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

So I thought I’d try to code out some of the simpler cases out right off the bat instead of looping through those numbers, but I wonder if this would be able to handle larger cases. Am I just wasting my time with these additional actions?

function primeFinder(n) {
  // Write your code here
  const commonDiv = [2, 3, 5, 7];
  
  // Validate parameter > 1
  if (n === 1) {
    return null;
  }

  // Get initial list
  const prime = commonDiv.filter(number => number <= n);
  
  // Confirm if paramater > 10
  if (n <= 10) {
    return prime;
  }

  for (let i = 11; i <= n; i++) {
    if (!commonDiv.some(number => i % number === 0)) {
      prime.push(i);
    }
  }

  return prime;
}

console.log(primeFinder(50))

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

I also tried making a reusable prime number ID’er function which would be used to populate an array. I originally made the function check if ‘n’ was itself actually a prime number (why use resources if it isn’t?), but that seemed to complicate the testing. Let me know what you think.

const primeFinder = n => { let primes = []; const isPrime = n => { let divisors = 0; for (let i=1; i<=n; i++) { if (n % i === 0) { divisors++; } } if (divisors === 2) { return true; } else { return false; } } for (let i=2; i<=n; i++) { if (isPrime(i)) { primes.push(i) }; } return primes; } // Have a nice day console.log(primeFinder(11)) // Leave this so we can test your code: module.exports = primeFinder;

Tried this challenge with while loops. It is a bit longer than other solutions but it gets the job done, so i’m still proud.

function primeFinder(n) {
  // Input primary check. No numbers below 2 allowed.
  if (n < 2) {
    return 'There are no prime numbers below 2.'
  }

  const primeNumbArray = [
    2
  ];
  let counter = primeNumbArray[primeNumbArray.length - 1];
  
  while (counter <= n) {
    let index = 0;
    let loopSwitch = true;
    // Test: Can "counter" be divided with a 0 remainder by any number in "primeNumbArray"?
    while (loopSwitch) {
      if (!primeNumbArray[index]) {
        // no: "counter" is a prime number
        primeNumbArray.push(counter)
      }
      if (primeNumbArray[index] && counter % primeNumbArray[index]) {
        index++
      } else {
        // yes: "counter" is a multiple of a prime number already stored.
        counter++;
        loopSwitch = false
      }
    }
  }
  
  return primeNumbArray
}

console.log(primeFinder(100));

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

Edit: after watching other solutions i realized my code had some redundant body fat that could be removed. There’s always room for improving.

function primeFinder(n) { if (typeof n !== 'number' || Number.isNaN(n)) { return 'Please insert a number.' } if (n < 2) { return 'There are no prime numbers below 2.' } const primeNumbs = []; function isPrime(num) { for (let i = 0; i < primeNumbs.length; i++) { if (num % primeNumbs[i] === 0) { return false } } return true } for (let counter = 2; counter <= n; counter++) { if (isPrime(counter)) { primeNumbs.push(counter) } } return primeNumbs } console.log(primeFinder(11)); // Leave this so we can test your code: module.exports = primeFinder;
function primeFinder(n) { let array = []; for (let i = 2; i <= n; i++) { array.push(i); } let prime = array.filter((n) => { if ( n === 2 || n === 3 || n === 5 || n === 7 || (n / n === 1 && n % 2 !== 0 && n % 3 !== 0 && n % 5 !== 0 && n % 7 !== 0 ) ) return n; }); return prime; } console.log(primeFinder(100))
function primeFinder(n) {
  let primes = [];
  for (let i = 1; i <= n; i++) {
    let factors = [];
    // Find factors of i
    for (let j = 1; j <= i; j++) {
      // If no remainder then factor
      if (i % j === 0) {
        factors.push(j);
      }
    }
    // Prime numbers only have 2 factors - 1, p
    if (factors.length === 2) {
      // If number has 2 factors one is 1 if other is p then prime
      if (factors.includes(i)) {
        primes.push(i);
      }
    }
  }
  return primes;
}

console.log(primeFinder(11))

// Leave this so we can test your code:
module.exports = primeFinder;
function primeFinder(n) {
  let newArray = [];

  for(let index = 1; index <= n; index++) {
    let flag = 0;

    for(let index2 = 2; index2 <= index; index2++) {
      ((Number.isInteger(index / index2)) ? flag++ : null);
    }

    ((flag === 1) ? newArray.push(index) : null)
  }
  return newArray;
}

Hey, @utku1522979306 welcome to the forums.

What problem are you having with your code?

function primeFinder(n) { let primes = []; for (let i = 2; i <= n; i++) { if (isPrime(i, 2)) { primes.push(i) } } return primes; } // isPrime takes two integers and returns a Boolean. p is the target int and n is the iterator seeded as 2, the smallest prime number function isPrime(p, n) { // if 0 or 1 then not prime if (p == 0 || p == 1) { return false; } // if p is equal to iterator then I have exhausted all the possibilities and its prime if (p == n) { return true; } // if the p mod n is zero then not prime if (p%n == 0) { return false } // recursive function: increment the iterator and try again until true or false return isPrime(p, n+1); } console.log(primeFinder(11));

I reuse this isPrime function for all my prime number challenges. I can’t remember where I found it but I translated it from python into go and now javascript.

function primeFinder(n) {
// Write your code here

const primearray = ;

for(let i = 1; i <= n; i++){
if(isPrime(i)){
primearray.push(i);
}

}
return primearray;
}

const isPrime = (n) => {
if(n === 1){
return false;

} else if ( n === 2){
  return true;
}

for(let i = n - 1; i > 1; i--){
  if(n % i === 0){
    return false;
  }


}
    return true;

}

console.log(primeFinder(11))

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

function primeFinder(n) {
  // Write your code here
  let results = new Array();

  //test each number, i, from 2 to n
  for (let i = 2; i <= n; i++)
  {
    let prime = true;
    //test from 2 to i
    for (let j = 2; j < i; j++)
    {  
      if (i%j == 0)
      {
        prime = false;       
      }
    }
    if (prime == true)
    {
      results.push(i);
    }
  }
  return results;
}
// Leave this so we can test your code:
module.exports = primeFinder;

This is my solution.
First I create a function to check if it is prime or no.
So, I aply this function in any number.

function primeFinder(n) {
  // Write your code here
  const prime_list = []
  function check(number){
    if(number < 2){
      return false
    }
    for (let i = 2; i < number; i++) {
      if (number%i === 0){
        return false
      }
    }
    return true
  }
  for (let i = 0; i <= n; i++) {
      if (check(i)){
        prime_list.push(i)
      }
    }
  return prime_list
}
console.log(primeFinder(11))

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