Tell us what’s happening:
Recently stared coding in JS, no prior coding experience to speak of although almost finished the legacy JS course. Need help checking my code as to me it looks “okay-ish” although there is an issue. Problem description: potential infinite loop warning at line 33 however it does run for the lower prime number indexes. Some explanation: the max value of 2120 is arbitrary just to generate prime numbers. Interesting this value triggers the potential infinite loop. Any tips/clues are very welcome to fix this warning (please no solutions just hints, need to learn)
Cheers.
Your code so far
function nthPrime(n) {
// need an array to find the index
// need prime check function and if prime copy to array
// check nth-index and return prime number
//determines if number is prime
function isPrime(a) {
if (a <= 1) return false;
for (let i = 2; i <= Math.sqrt(a); i++) {
if( a % i === 0) return false;
}
return true;
}
//generate numbers and check if prime via function isPrime
//if prime copy to array
function generatePrimes(a) {
let primes = [];
for ( let i = 2; i <= a; i++) {
if (isPrime(i)) primes.push(i);
}
return primes;
}
function lookupPrime (x, y) {
return x.at(y);
}
//main
let max = 2120; // maximum limit to generate prime number range
let d = [];
for (let j = 2; j <= max; j++) {
d = generatePrimes(j);
}
//get value of nth-index
let lookUp = (n - 1); // nth - 1 as index starts at 0;
let z = lookupPrime(d, lookUp) // get value of index
return z;
}
nthPrime(100);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0
Challenge Information:
Project Euler Problems 1 to 100 - Problem 7: 10001st prime