What’s happening:
I don’t know why the code doesn’t seem to work with 10001 on fcc, but using node it does. Someone has any idea of why?
Thanks
My code so far
const nthPrime = (number) => {
let primes = [2];
for(let i = 3; primes.length <= number; i+= 2) {
if(primes.every(v => i % v !== 0)) {
primes.push(i);
if(primes.length === number) return i;
}
}
}
nthPrime(10001);
My browser information:
User Agent is: Chrome/68.0.3440.84
.
Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-7-10001st-prime
The fcc editor thinks that you have a possible infinite loop, so it refuses to run. As far as I know the option to disable that hasn’t been implemented yet
Does //noprotect
not work anymore or something?
Is 100ms a reasonable limit for this question?
Fwiw with the naïve sieve of Eratosthenes you would need an array of over 100000 elements
You are totally right, I just optimize the code a bit:
const nthPrime = (number) => {
let primes = [2];
let higherDivisorLimit;
let isPrime;
for(let i = 3; primes.length < number; i+=2) {
higherDivisorLimit = Math.sqrt(i) + 1;
isPrime = true;
for(let j = 0; primes[j] < higherDivisorLimit; j++) {
if(i % primes[j] === 0) {
isPrime = false;
break;
}
}
if(isPrime) primes.push(i);
}
return primes[primes.length - 1];
}
nthPrime(10001);
I just discovered, after reading a bit, I just needed to compare the numbers up to their square root. All divisors higher than that will have a rest equal to a smaller divisor (I think I studied that at primary school, haha).
1 Like
Nice. Thanks for sharing your solution. really helped me