Skip to content

Instantly share code, notes, and snippets.

@netroy
Forked from rakeshpai/primes.js
Created September 16, 2013 21:24
Show Gist options
  • Save netroy/6586793 to your computer and use it in GitHub Desktop.
Save netroy/6586793 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