Created
March 21, 2016 10:54
-
-
Save jezhou/445411e15fdaf7b2425b to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes, raw javascript implementation
This file contains hidden or 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
n = 10; | |
var nlist = []; | |
// Generate the list of desired numbers | |
for(var i = 2; i < n; i++){ | |
nlist.push(true); | |
} | |
// Mark each non-prime as false | |
var x = 2; | |
for(var i = 2; i < Math.sqrt(n); i++){ | |
if(nlist[i]){ | |
for(var j = i*i; j < n; j += i){ | |
nlist[j] = false; | |
} | |
} | |
} | |
// Print out all index numbers correlated to true values | |
var primes = []; | |
for(var i = 2; i < n; i++){ | |
if(nlist[i]){ | |
primes.push(i) | |
} | |
} | |
console.log(primes); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment