Tell us what’s happening:
My code cannot pass the test: nthPrime(10001)
It stops at i = 94709 and it should pass the test if it can reach 104743.
I cannot think of any way to improve the speed of the algorithm.
Please help.
Your code so far
function nthPrime(n) {
let primeList = [2];
let i = 3;
while(primeList.length < n){
let j = 0;
let isPrime = true;
let bound = parseInt(Math.sqrt(i));
while(primeList[j] <= bound){
if(i % primeList[j] == 0){
isPrime = false;
break;
}
j++;
}
if(isPrime){
primeList.push(i);
}
i+=2;
}
return primeList[primeList.length - 1];
}
console.log(nthPrime(10001));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.92 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-7-10001st-prime/