Prime Sieve Of Eratosthenes Segmented Typed
Generate all primes up to n using a typed segmented sieve of Eratosthenes for memory efficiency.
Code
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 < 2short-circuits the flow with an earlyreturnwhen 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
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.Number FormatterFormat numbers with thousands grouping, fixed decimals, custom separators, and an optional prefix or suffix.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.