Last active
June 29, 2018 13:00
-
-
Save chrisdothtml/1f37849c020161fe08f1b41be28d6013 to your computer and use it in GitHub Desktop.
Generate 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
/** | |
* Generate Set of prime numbers up to `maxPrime` | |
* https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes | |
* | |
* @param {Number} maxPrime | |
* @returns {Set} | |
*/ | |
function getPrimes (maxPrime) { | |
const sieve = new Map | |
const result = new Set | |
let currNum, i | |
// initially make all numbers possibly prime | |
for (i = 2; i <= maxPrime; i++) sieve.set(i, 1) | |
for (currNum = 2; currNum <= maxPrime; currNum++) { | |
if (sieve.get(currNum) === 1) { | |
result.add(currNum) | |
// mark all multiples as non-prime | |
for (i = currNum * 2; i <= maxPrime; i += currNum) { | |
sieve.set(i, 0) | |
} | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment