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, , and for all up to in a single pass.
How It Works
- If : ,
- If : ,
Computed Arrays
isPrime[i] — whether is primeprime[] — list of all primes spf[i] — smallest prime factor of (allows factorization)phi[i] — Euler's totient mobius[i] — Möbius function When to Use
spf allows factoring any in