Skip to content

Instantly share code, notes, and snippets.

@rakeshpai
Last active December 22, 2015 21:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rakeshpai/6533842 to your computer and use it in GitHub Desktop.
Save rakeshpai/6533842 to your computer and use it in GitHub Desktop.
var primes = [2];
var n = 3; // The number we are testing. Will be incremented.
function checkNextNumber() {
// It's sufficient to check if there are any prime factors up to sqrt(n)
n++;
var limitForChecking = Math.floor(Math.sqrt(n));
var isPrime = true;
for(var i=0;i<primes.length;i++) {
if(primes[i] > limitForChecking) {
break;
} else if(n % primes[i] === 0) {
isPrime = false;
break;
}
}
if(isPrime) {
console.log("Found prime:", n);
primes.push(n);
}
setTimeout(checkNextNumber, 0);
}
checkNextNumber();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment