Created
May 24, 2021 14:04
-
-
Save c7x43t/a02b6420cdd67dac488656a3b0fe5a87 to your computer and use it in GitHub Desktop.
Fast Prime test
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 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