guest@cp-base:~/home/number-theory$
templates/sieve.cpp
compilable
$cat templates/sieve

Sieve of Eratosthenes

Linear sieve computing primes, smallest prime factor (SPF), Euler's totient, and Mobius function in O(n).

#sieve#prime#number-theory#totient#mobius
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

vector<bool> isPrime;
vector<int> prime, spf, phi, mobius;

void sieve(int n) {
    isPrime.assign(n + 1, true);
    spf.assign(n + 1, 0);
    phi.assign(n + 1, 1);
    mobius.assign(n + 1, 1);
    isPrime[0] = isPrime[1] = false;
    spf[1] = 1;

    for (int i = 2; i <= n; i++) {
        if (isPrime[i]) {
            prime.push_back(i);
            spf[i] = i;
            phi[i] = i - 1;
            mobius[i] = -1;
        }
        for (int p : prime) {
            if ((ll)i * p > n) break;
            isPrime[i * p] = false;
            spf[i * p] = p;
            if (i % p == 0) {
                phi[i * p] = phi[i] * p;
                mobius[i * p] = 0;
                break;
            }
            phi[i * p] = phi[i] * (p - 1);
            mobius[i * p] = -mobius[i];
        }
    }
}
36 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Linear Sieve

Computes primes, smallest prime factor, φ(n)\varphi(n), and μ(n)\mu(n) for all nn up to NN in a single O(N)O(N) pass.

How It Works

  • Each composite is marked exactly once — by its smallest prime factor

  • For each ii, iterate over discovered primes pp. Mark ipi \cdot p as composite and set spf[ip]=p\text{spf}[i \cdot p] = p

  • Break when pip \mid i — this is the key invariant that ensures linear time

  • φ\varphi and μ\mu are computed multiplicatively during the sieve:

  • - If pip \mid i: φ(ip)=φ(i)p\varphi(ip) = \varphi(i) \cdot p, μ(ip)=0\mu(ip) = 0
    - If pip \nmid i: φ(ip)=φ(i)(p1)\varphi(ip) = \varphi(i) \cdot (p-1), μ(ip)=μ(i)\mu(ip) = -\mu(i)

    Computed Arrays

  • isPrime[i] — whether ii is prime

  • prime[] — list of all primes N\le N

  • spf[i] — smallest prime factor of ii (allows O(logn)O(\log n) factorization)

  • phi[i] — Euler's totient φ(i)\varphi(i)

  • mobius[i] — Möbius function μ(i)\mu(i)
  • When to Use

  • Precomputing factorizations — spf allows factoring any nNn \le N in O(logn)O(\log n)

  • Batch φ\varphi or μ\mu queries

  • Prime counting, prime enumeration

  • Multiplicative function sieves in general
  • Complexity

  • Time — O(N)O(N)

  • Space — O(N)O(N)