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 #get-help.

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

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

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 #community:Codecademy-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;
1 Like

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;