Last active
December 22, 2015 21:29
-
-
Save rakeshpai/6533842 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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