Project Euler Problems 1 to 100 - Problem 7: 10001st prime

Tell us what’s happening:
I filter the primes for the divisible Numbers. Hence if the divisible numbers array is 0,the number is a prime number, as it is not divisible by any of the other prime numbers withh modulus === 0.

I haven’t found a mistake here.

Your code so far

function nthPrime(n){

  let primes = [2]
  let testNumber = 3

  while(primes.length <= n){  
    console.log(primes)
    let filteredPrimes = primes.filter( x => testNumber%x === 0) 
    if(filteredPrimes.length === 0){
      primes.push(testNumber)
      testNumber++
    }else{
      testNumber++
    }
  }

  return primes[primes.length - 1]

}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36

Challenge: Project Euler Problems 1 to 100 - Problem 7: 10001st prime

Link to the challenge:

This is one problem! Do you want the length to exceed n?

This will drastically slow down your code. You should comment it out when running the tests!


If you fix those two things, you will pass almost every test. But, you will still not quite pass the last one because your approach isn’t fast enough for very large inputs.

You can fix this one of two ways

  1. Use a faster approach

  2. Use an alternative to this expensive filter


here are small formatting fixes:

function nthPrime(n) {
  const primes = [2];
  let testNumber = 3;

  while (primes.length <= n) {
    const filteredPrimes = primes.filter(x => testNumber % x === 0);
    if (filteredPrimes.length === 0) {
      primes.push(testNumber);
    }
    testNumber++;
  }

  return primes[primes.length - 1];
}

Hi thanks for the answer. :))

It is still odd that it is not going trough.
Ah, the while loop keeps on adding the testNumber until we have added n primes into the array. :))

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.