Skip to content

Instantly share code, notes, and snippets.

@jezhou
Created March 21, 2016 10:54
Show Gist options
  • Save jezhou/445411e15fdaf7b2425b to your computer and use it in GitHub Desktop.
Save jezhou/445411e15fdaf7b2425b to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes, raw javascript implementation
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