Skip to content

Instantly share code, notes, and snippets.

@edulan
Created July 19, 2018 09:10
Show Gist options
  • Save edulan/66c39c70d36bd29b73199627678f086b to your computer and use it in GitHub Desktop.
Save edulan/66c39c70d36bd29b73199627678f086b to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
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