Last active
January 31, 2016 15:23
-
-
Save svagi/6113e0eddcbe1f38be61 to your computer and use it in GitHub Desktop.
Function for finding all prime numbers up to any given limit (Sieve of Eratosthenes)
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
function getPrimes (n) { | |
const sieve = new (Uint32Array || Array)(n + 1); | |
const primes = []; | |
const length = sieve.length; | |
const limit = Math.floor(Math.sqrt(n + 1)) | |
let p = 0; | |
let m = 0; | |
for (p = 2; p <= limit; p++) { | |
for (m = p * 2; m < length; m += p){ | |
sieve[m] = 1; | |
} | |
} | |
for (p = 2; p <= length; p++){ | |
if (!sieve[p]){ | |
primes.push(p); | |
} | |
} | |
return primes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment