B · Master · 13 min

Sieve and Factorization

The linear-looking nested loop of the Sieve of Eratosthenes marks composites in O(n log log n). After that, smallest-prime-factor arrays factor any k ≤ n in O(log k).

Trial division tests primality of n in O(√n). Fine once. Dead if you do it for every value in 1..n at n = 1e6 (∑ √k is not your friend — that is O(n^{3/2})).

The sieve marks multiples of each prime p starting at p*p. Time O(n log log n), memory O(n). CSES Counting Divisors / Sum of Divisors assume you *precompute* something of size n, not that you factor each query from scratch.

Constraint gate: n ≤ 1e7 is a typical sieve. n ≤ 1e12 means you sieve √n and factor one number, or you segment-sieve a range.

Sieve + SPF factorizationjs
function sieve(n) {
  const isPrime = Array(n).fill(true);
  isPrime[0] = isPrime[1] = false;
  for (let p = 2; p * p < n; p++) {
    if (!isPrime[p]) continue;
    for (let q = p * p; q < n; q += p) isPrime[q] = false;
  }
  return isPrime;
}

function spfTable(n) {
  const spf = Array.from({ length: n }, (_, i) => i);
  for (let p = 2; p * p < n; p++) {
    if (spf[p] !== p) continue;
    for (let q = p * p; q < n; q += p) if (spf[q] === q) spf[q] = p;
  }
  return spf;
}

TRACE

Sieve primes < 20. Mark multiples of 2, then 3.

Start

0,1 composite. 2..19 unmarked (true).

1 / 4

CHECK

Why start the inner loop at p*p instead of 2p?

CHECK

q = 1e5 queries, each 'factorize x' with x ≤ 1e6. What do you precompute?

Checks 0/2

Next lesson