Technique
Sieve of Eratosthenes / Smallest Prime Factor
Mark composites up to N in O(N log log N) (or store smallest prime factors) to list primes and factorise many numbers fast.
Learn firstMath / Number TheoryUnlocksMobius Inversion & Multiplicative Functions
0%
mastery
0/9 solved
0/9 solved
Recognise it
The signal
count primes below N
1Brute force
Trial division per number O(sqrt n).
2The observation
Repeated trial division: each composite is marked by its prime factors once.
3Why it works
After processing p, every composite with smallest prime p is marked.
Reach for it when
- +factorise many numbers <= 1e7
- +divisor counts / totients for all numbers
Not when
- ×single huge number (trial division up to sqrt, or Pollard rho)
Practice
0/9 solved
- T-primesCodeforces1300
- Counting Coprime PairsCSESMedium
- Count PrimesMedium
- Counting DivisorsCSESMedium
- Split a Digit String into PrimesSnowflake, AmazonOAMedium
- GCD SubsetsCSESHard
- Coprime SubsequencesCodeforces2000
- Two DivisorsCodeforces2000
- SUM and REPLACECodeforces2000
Pitfalls
Misconceptions
- !starting marking at 2p instead of pp is correct but slower; overflow of pp
Go deeper1 combinations · resources
Combinations
Mobius Inversion & Multiplicative Functions+Sieve of Eratosthenes / Smallest Prime Factor+Combinatorics mod p (nCr, Catalan, stars and bars)
count pairs/subsequences with gcd 1 (or gcd exactly g), values <= 1e6
- Mobius Inversion & Multiplicative Functions:
- invert 'divisible by d' counts into 'gcd exactly 1'
- Sieve of Eratosthenes / Smallest Prime Factor:
- a linear sieve for mu (and the multiples counts)
- Combinatorics mod p (nCr, Catalan, stars and bars):
- count pairs C(c_d, 2) or subsets 2^c_d - 1 from c_d multiples