|
| 1 | +import assert from 'node:assert/strict'; |
| 2 | + |
| 3 | +const findPrimesBelow = 1_000_000; |
| 4 | +const expectedPrimes = 78_498; |
| 5 | + |
| 6 | +// byteLength of |
| 7 | +// BSON.serialize({ primes: Buffer.from(new Int32Array(sieveOfEratosthenes(findPrimesBelow)).buffer) }).byteLength) |
| 8 | +// a bin data of int32s |
| 9 | +const byteLength = 314_010; |
| 10 | + |
| 11 | +export const taskSize = 3.1401000000000003; // ~3MB worth of work |
| 12 | + |
| 13 | +assert.equal(taskSize, byteLength * 10e-6); // taskSize should stay hardcoded, checking here the math is done right. |
| 14 | + |
| 15 | +/** @see https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes */ |
| 16 | +export function sieveOfEratosthenes(n: number) { |
| 17 | + // Create a boolean array "prime[0..n]" and initialize |
| 18 | + // all entries as true. A value in prime[i] will |
| 19 | + // become false if i is Not a prime |
| 20 | + const prime = Array.from({ length: n + 1 }, () => true); |
| 21 | + |
| 22 | + // We know 0 and 1 are not prime |
| 23 | + prime[0] = false; |
| 24 | + prime[1] = false; |
| 25 | + |
| 26 | + for (let p = 2; p * p <= n; p++) { |
| 27 | + // If prime[p] is not changed, then it is a prime |
| 28 | + if (prime[p] === true) { |
| 29 | + // Update all multiples of p as false |
| 30 | + for (let i = p * p; i <= n; i += p) { |
| 31 | + prime[i] = false; |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + // Collecting all prime numbers |
| 37 | + const primes = []; |
| 38 | + for (let i = 2; i <= n; i++) { |
| 39 | + if (prime[i] === true) { |
| 40 | + primes.push(i); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return primes; |
| 45 | +} |
| 46 | + |
| 47 | +export async function run() { |
| 48 | + assert.equal(sieveOfEratosthenes(findPrimesBelow).length, expectedPrimes); |
| 49 | +} |
0 commit comments