Skip to content

Instantly share code, notes, and snippets.

@c7x43t
Created May 24, 2021 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c7x43t/a02b6420cdd67dac488656a3b0fe5a87 to your computer and use it in GitHub Desktop.
Save c7x43t/a02b6420cdd67dac488656a3b0fe5a87 to your computer and use it in GitHub Desktop.
Fast Prime test
var primes=[2];
var maxPrime=2;
function generatePrimes(max){
for(var i=maxPrime;i<=max;i++){
maxPrime=i;
if(isPrime(i)) if(i>2) primes.push(i);
}
}
function isPrime(n){
var max=Math.floor(Math.sqrt(Math.abs(n)));
if(maxPrime<max) generatePrimes(max);
for(var i=0;i<primes.length;i++){
var prime=primes[i];
if(prime<=max){
if((n/prime)%1===0) return false;
}else{
break;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment