Created
July 19, 2018 09:10
-
-
Save edulan/66c39c70d36bd29b73199627678f086b to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
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
function * generateMultiplesOf (number) { | |
for (let factor = 2;; factor++) { | |
yield number * factor | |
} | |
} | |
function * generatePrimes (maxNumber = 1000) { | |
const firstPrime = 2 | |
const nonPrimeNumbers = new Set() | |
for (let nextPrime = firstPrime; nextPrime < maxNumber; nextPrime++) { | |
if (nonPrimeNumbers.has(nextPrime)) { | |
continue | |
} | |
const multiples = generateMultiplesOf(nextPrime) | |
for (let nextMultiple of multiples) { | |
if (nextMultiple > maxNumber) { | |
break | |
} | |
nonPrimeNumbers.add(nextMultiple) | |
} | |
yield nextPrime | |
} | |
} | |
function floorPrime (number) { | |
const primes = generatePrimes(number) | |
return [...primes].slice(-1)[0] | |
} | |
const primes = generatePrimes() | |
console.log(primes.next().value) | |
console.log(primes.next().value) | |
console.log(primes.next().value) | |
console.log(floorPrime(32432)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment