General form
THEOREM
For finite sets ,
Equivalently,
For
For :

Proof
Pick an element and suppose it lies in exactly of the sets .
Then on the right-hand side:
- is counted in exactly single sets,
- subtracted in exactly pairwise intersections,
- added in exactly triple intersections,
- and so on.
So the total contribution of to the right-hand side is
Using
we get
So every element in the union is counted exactly once. An element outside the union has , so it contributes on both sides. Therefore both sides count exactly the same elements with the same multiplicity, which proves the formula.
Enumerating the subsets in code
In programming problems, the sets in the inclusion-exclusion formula are usually traversed with a bitmask.
For n sets, every integer mask from 1 to (1 << n) - 1 represents one non-empty subset of :
- bit
iis1if and only if the subset contains thei-th set Integer.bitCount(mask)gives the size of the subset- odd subset size means add the intersection term
- even subset size means subtract the intersection term
For divisibility problems, if is the set of numbers divisible by a[i], then for a chosen subset the intersection size is often computed with the lcm:
Example:
public static void testCase() {
int n = In.readInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = In.readInt();
}
long N = (long) Math.pow(10, 10), res = N;
for (int mask = 1; mask < (1 << n); mask++) {
long lcm = 1;
int bits = Integer.bitCount(mask);
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
lcm = (lcm * a[i]) / gcd(lcm, a[i]);
}
}
res = bits % 2 == 1 ? res - N / lcm : res + N / lcm;
}
Out.println(res);
}
public static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}Here:
- the loop over
maskenumerates all non-empty subsets bitsis the subset sizelcmrepresents the intersection of the chosen divisibility setsN / lcmis the number of integers in1..Ndivisible by all chosen numbers- since
resstarts asN, this code computes how many integers in1..Nare divisible by none of the numbers ina