Skip to content

Instantly share code, notes, and snippets.

@nermin99
Last active March 11, 2025 10:48
Show Gist options
  • Save nermin99/49c56a9919b60339bc0729e01df46bf1 to your computer and use it in GitHub Desktop.
Save nermin99/49c56a9919b60339bc0729e01df46bf1 to your computer and use it in GitHub Desktop.
JavaScript Prime Number Generator
function* nats(n) {
yield n
yield* nats(n + 1)
}
function* sieve(gen) {
const n = gen.next().value
yield n
yield* sieve((function* () {
for (const i of gen) {
if (i % n !== 0) {
yield i
}
}
})())
}
const prime = sieve(nats(2))
console.log(prime.next().value) // 2
console.log(prime.next().value) // 3
console.log(prime.next().value) // 5
console.log(prime.next().value) // 7
console.log(prime.next().value) // 11
@nermin99
Copy link
Author

A recursive solution using js generators

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment