Count a union by adding the parts, subtracting the double-counted pairs, adding back the triples, and so on.
Equivalently, for the complement — usually the more useful form:
Why the signs work
Fix an element belonging to exactly of the sets. It is counted once for every subset of those sets, with sign , giving
so it contributes exactly to the complement count — as it should, since it is in at least one set. An element in none of the sets contributes only through , i.e. .
The whole method is that one binomial identity.
The direct implementation
long long countCoprimeUpTo(long long n, vector<long long> primes) {
int k = primes.size();
long long total = 0;
for (int mask = 0; mask < (1 << k); mask++) {
long long prod = 1;
for (int i = 0; i < k; i++) if (mask >> i & 1) prod *= primes[i];
int bits = __builtin_popcount(mask);
total += (bits % 2 ? -1 : 1) * (n / prod);
}
return total;
}. Since , any has at most 15 distinct prime factors, so the enumeration is small.
Standard applications
| Problem | Setup |
|---|---|
| Count integers in coprime to | = divisible by the -th prime factor of — gives Euler’s totient |
| Count integers divisible by none of | = divisible by ; intersections use |
| Derangements | = ” is a fixed point” |
| Surjections from to | = ” is not hit”: |
| Count permutations avoiding forbidden positions | rook polynomials |
| Paths avoiding a set of cells | subtract paths through each cell |
| Colourings with all colours used | surjection count |
| Distinct values in a range | Mobius-weighted counting |
| Count -tuples with |
The Möbius connection
Möbius inversion is inclusion-exclusion on the divisor lattice: is exactly the sign, and squarefree correspond to the subsets . Whenever a problem is “count things coprime to / not divisible by”, the Möbius form
is inclusion-exclusion written compactly, and it runs in instead of .
long long coprimePairs(int n) { // pairs (a,b) in [1,n]^2 with gcd 1
long long res = 0;
for (int d = 1; d <= n; d++) res += (long long)mu[d] * (n / d) * (n / d);
return res;
}When is too large
The direct sum is exponential in the number of sets. Three ways out:
| Situation | Technique |
|---|---|
| Sets indexed by divisors | Möbius — linear in |
| The intersection size depends only on | collapse to |
| Sets form a lattice or poset | Möbius function of that poset |
| Subset sums needed for all masks | SOS DP, |
| Only a few sets actually overlap | build a graph and handle components separately |
The second row is the most common escape: in derangements and surjections, depends only on , which turns terms into .
The Bonferroni inequalities
Truncating the alternating sum gives bounds, not just an exact value: stopping after an even number of terms underestimates the union, after an odd number overestimates it. Useful when the full sum is intractable but a bound suffices.
Why it is worth knowing
It converts “count things satisfying none of these conditions” — usually hard — into “count things satisfying each subset of conditions” — usually easy, because intersections are simple constraints. That reframing is the core of most counting problems in contests, and it is the bridge to Möbius inversion, SOS DP, and the derangement family.
See also: Combinatorics · Möbius Function · SOS DP · Derangements