Created
July 18, 2024 06:37
-
-
Save divs1210/954579c5f9a3ec721f4f79a74bf6f0ce to your computer and use it in GitHub Desktop.
Memoized first N primes in JS
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
const any = (arr, f) => { | |
for (const x of arr) { | |
if (f(x)) | |
return true; | |
} | |
return false; | |
} | |
const KNOWN_PRIMES = [2]; | |
const primes = (n) => { | |
if (n < 0) | |
throw new Error("n should be >= 0"); | |
while (KNOWN_PRIMES.length < n) { | |
let curr = KNOWN_PRIMES.at(-1) + 1; | |
while (any(KNOWN_PRIMES, prime => curr % prime === 0)) | |
curr++; | |
KNOWN_PRIMES.push(curr); | |
} | |
return KNOWN_PRIMES.slice(0, n); | |
} | |
console.log(primes(10)); | |
// [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment