Created
July 8, 2012 03:22
-
-
Save grownseed/3069161 to your computer and use it in GitHub Desktop.
JavaScript Euler's sieve implementation for generating an array of prime numbers
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
/* | |
To return an array of all prime numbers below 1000: | |
primeRange(1000); | |
*/ | |
function primeRange(max) | |
{ | |
var max_sqrt = Math.sqrt(max), | |
range = [], | |
current = 0; | |
//generate array of numbers | |
for (i = 2; i <= max; i++) | |
range.push(i); | |
//filter multiples out | |
while (range[current] <= max_sqrt) | |
{ | |
range = range.filter(function(n) | |
{ | |
return (n == range[current] || n % range[current] != 0); | |
}); | |
current++; | |
} | |
return range; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment