Prime Sieve Of Eratosthenes Segmented Typed

Generate all primes up to n using a typed segmented sieve of Eratosthenes for memory efficiency.

TypescriptData Integrity

Code

typescriptsnippet
11 lines
function segmentedSieve(n: number): number[] {
  if (n < 2) return [];
  const limit = Math.floor(Math.sqrt(n)) + 1;
  const basePrimes: number[] = [];
  const isComp = new Array(limit).fill(false);
  for (let i = 2; i < limit; i++) { if (!isComp[i]) { basePrimes.push(i); for (let j = i * i; j < limit; j += i) isComp[j] = true; } }
  const primes = [...basePrimes];
  const segSize = 1 << 15;
  for (let low = limit; low <= n; low += segSize) { const high = Math.min(low + segSize - 1, n); const seg = new Array(high - low + 1).fill(false); for (const p of basePrimes) { let start = Math.ceil(low / p) * p; for (let j = start; j <= high; j += p) seg[j - low] = true; } for (let i = 0; i < seg.length; i++) if (!seg[i] && low + i >= 2) primes.push(low + i); }
  return primes;
}

How it works

Prime Sieve Of Eratosthenes Segmented Typed comes down to the function segmentedSieve.

Iteration is nested: for (let i = 2; i < limit; i++) { if (!isComp[i]) { basePrimes.push(i); for (let j = i * i; j < l… frames the pass, for (let low = limit; low <= n; low += segSize) { const high = Math.min(low + segSize - 1, n); co… does the per-item step.

The result is a fresh construction, so callers can keep their originals.

What to watch for

  • The guard n < 2 short-circuits the flow with an early return when its condition holds.

Applying it

The primary signature is function segmentedSieve(n: number)

Statements that matter

if (n < 2) return [];

Interactive Tools for This Topic

FAQ

Does `segmentedSieve` modify its input?
No mutation happens — the function reads its input and returns a new value.
Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `segmentedSieve` at load time.