Skip to content

Instantly share code, notes, and snippets.

@OpenGrid
Last active December 19, 2015 00:49
Show Gist options
  • Save OpenGrid/5871665 to your computer and use it in GitHub Desktop.
Save OpenGrid/5871665 to your computer and use it in GitHub Desktop.
Simple Prime Sieve
function getPrimes(howMany) {
var primes = [];
var isPrime, primesCount = 0, candidate, primeIndex;
for (candidate = 2; primesCount < howMany; candidate++) {
for(primeIndex = 0, isPrime = true;
primeIndex < primesCount && primes[primeIndex] <= Math.sqrt(candidate);
primeIndex++) {
if (candidate % primes[primeIndex] === 0) {
isPrime = false;
break;
}
}
if(isPrime) {
primes.push(candidate);
primesCount++;
}
}
return primes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment