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 i is 1 if and only if the subset contains the i-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 mask enumerates all non-empty subsets
  • bits is the subset size
  • lcm represents the intersection of the chosen divisibility sets
  • N / lcm is the number of integers in 1..N divisible by all chosen numbers
  • since res starts as N, this code computes how many integers in 1..N are divisible by none of the numbers in a