Last active
March 11, 2025 10:48
-
-
Save nermin99/49c56a9919b60339bc0729e01df46bf1 to your computer and use it in GitHub Desktop.
JavaScript Prime Number Generator
This file contains hidden or 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* 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A recursive solution using js generators