Prime Sieve Of Eratosthenes Segmented (JavaScript)
Generate all primes up to n using a segmented sieve of Eratosthenes for memory efficiency on large ranges.
Code
function segmentedSieve(n) {
if (n < 2) return [];
const limit = Math.floor(Math.sqrt(n)) + 1;
const basePrimes = [];
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
Count the function segmentedSieve as the entire surface area of Prime Sieve Of Eratosthenes Segmented (JavaScript).
The structure is a loop within a loop: for (let i = 2; i < limit; i++) outside, for (let low = limit; low <= n; low += segSize) inside.
The return value is newly constructed — inputs are never handed back.
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)
Statements that matter
if (!isComp[i]) { basePrimes.push(i); for (let j = i * i; j < limit; j += i) isComp[j] = true; }
for (let j = start; j <= high; j += p) seg[j - low] = true;
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.
- Anything to download besides the language toolchain?
- Nothing beyond the toolchain you already have for this language. The file defines `segmentedSieve` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.