Skip to content

Instantly share code, notes, and snippets.

@chrisdothtml
Last active June 29, 2018 13:00
Show Gist options
  • Save chrisdothtml/1f37849c020161fe08f1b41be28d6013 to your computer and use it in GitHub Desktop.
Save chrisdothtml/1f37849c020161fe08f1b41be28d6013 to your computer and use it in GitHub Desktop.
Generate prime numbers
/**
* 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