Skip to content

Instantly share code, notes, and snippets.

@mindplace
Created March 29, 2016 16:13
Show Gist options
  • Save mindplace/ad2d6dd52d89e32f6813 to your computer and use it in GitHub Desktop.
Save mindplace/ad2d6dd52d89e32f6813 to your computer and use it in GitHub Desktop.
function nthPrimeNumber(num) {
var primes = [0, 0, 2];
var max = Math.pow(10, 4);
for (var i=3; i < max + 1; i++) {
if (i % 2 == 0) {
primes.push(0);
} else {
primes.push(i);
}
}
var j = 3
while (true) {
// sieve
for (var k = j*j; k < primes.length; k += j) {
primes[k] = 0;
}
// finding the next item bigger than j to use for sieve
for (var x = j; x < primes.length; x += 1) {
if (primes[x] > j) {
j = x;
break;
}
}
// break condition
if (j*j > primes.length) {
break;
}
}
// gives back the primes array without zeros
primes = primes.filter(function(x){if (x > 0) {return x;}});
return primes[num - 1];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment