What is the solution of this program? does anyone know?

Tell us what’s happening:

Your code so far


function nthPrime(nth){
    var P= [2], n= 3, div, i, limit,isPrime;
    while(P.length<nth){
        div= 3, i= 1;
        limit= Math.sqrt(n)+1;
        isPrime= true;
        while(div<limit){
            if(n%div=== 0){
                isPrime= false;
                div= limit;
            }
            else div= P[i++] || div+ 2;
        }
        if(isPrime) P.push(n);
        n+= 2;
    }
    return P[P.length-1];
}

nthPrime(1000);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-7-10001st-prime

try this ```
function nthPrime(n) {

//Primes array which will store all the prime numbers
const primes = [2];

//Num is the number we want to check
let num = 3, isPrime = true;

//Looping until primes array is equal to n
while (primes.length < n){

//All the primes numbers of a number is always <= it's square root
let max = Math.ceil(Math.sqrt(num));

for (let i = 0; primes[i] <= max; i++){
  if (num % primes[i] == 0) {
    
    //Looping till we find the prime
    isPrime = false;
    break;
  }
}

//if Prime found, push it to the array
if (isPrime) primes.push(num);
isPrime = true;

//An optimization technique, since we know of all even numbers only 2 is a prime number, we can skip the rest
num+=2;

}

//Returning the last number
return primes[primes.length-1];

}

already tried , but it doesn’t shows the nth term of (10001)

1 Like

Oh, but that code helped me win that challange.