DEV Community

Discussion on: Project Euler #7 - 10001st prime

Collapse
 
maxart2501 profile image
Massimo Artizzu • Edited

JavaScript:

const primes = [ 2, 3 ];
function isPrime(n) {
  return primes.every(d => n % d > 0);
}

let i = 1;
while (primes.length < 10001) {
  const n = i * 3 + 1.5 + .5 * (-1) ** (i + 1);
  if (isPrime(n)) primes.push(n);
  i++;
}
console.log(primes[10000]); 

If some is wondering what in the world I'm doing to compute n, it's about this: every prime number larger than 3 is of the form 6 k ± 1. With a little manipulation it could be rewritten as 3/2 + 3 h + (-1)h + 1 / 2.