Technique · CP 2000
Mobius Inversion & Multiplicative Functions
Count pairs or subsets by gcd in two steps. First, for every d, count the items divisible by d (a harmonic sum, O(V log V)). Then invert: the exactly-gcd-1 count is the sum of mu(d)*f(d). A linear sieve gives mu, phi and divisor functions.
0/7 solved
Recognise it
The signal
count coprime pairs/subsequences
1Brute force
All pairs with gcd: O(n2 log V).
2The observation
The number of pairs.
3Why it works
The sum of mu(d) over d | n is [n = 1]. f(d) = number of multiples of d is easy to count, and the count with gcd exactly d follows by inversion.
Reach for it when
- +number of subsets with gcd exactly g
- +sum of gcd(a_i, a_j) over pairs
- +values up to 1e6 with n up to 1e5
Not when
- ×a single condition over at most ~20 primes (plain inclusion-exclusion)
Practice
- Counting Coprime PairsCSESMedium
- Divisor AnalysisCSESMedium
- Same GCDsCodeforces1800
- GCD SubsetsCSESHard
- Coprime SubsequencesCodeforces2000
- Mocha and StarsCodeforces2200
- Alex and a TV ShowCodeforces2500
Pitfalls
Misconceptions
- !iterating divisors of each element (O(n sqrt V)) instead of multiples of each d (O(V log V))
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