Skip to content

Instantly share code, notes, and snippets.

@divs1210
Created July 18, 2024 06:37
Show Gist options
  • Save divs1210/954579c5f9a3ec721f4f79a74bf6f0ce to your computer and use it in GitHub Desktop.
Save divs1210/954579c5f9a3ec721f4f79a74bf6f0ce to your computer and use it in GitHub Desktop.
Memoized first N primes in JS
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