Inclusion–exclusion principle

When several conditions overlap, simply adding the counts for each condition may count some objects more than once. The inclusion–exclusion principle corrects this by alternately adding and subtracting intersection sizes. It is especially useful when individual intersections are easy to count but the full range is too large to enumerate.

Counting a union of sets

How many numbers from 1 to 10 are divisible by 2 or by 3? There are 5 multiples of 2 and 3 multiples of 3, but 5 + 3 = 8 is too many: 6 is a multiple of both and was counted twice. Subtracting it once gives 5 + 3 − 1 = 7.

Venn diagram of the numbers 1 to 10: a blue circle holds the multiples of 2 (2, 4, 8, 10), a red circle holds the multiples of 3 (3, 9), 6 sits where the circles overlap, and 1, 5, 7 lie outside both circles.

Fig. 1. 5 + 3 counts 6 twice: it is in both circles.

The overlap is the multiples of 6, and there are 10 / 6 = 1 of them (integer division rounds down). A loop up to 10^{18} would run for centuries at about 10^8 simple steps per second, a common rule of thumb, while the formula needs one division per term.

Three overlapping sets

With the numbers from 1 to 36 and the divisors 2, 3 and 5, adding gives 18 + 12 + 7 = 37, more than the 36 numbers there are.

Do what worked for two: subtract every overlap of two. There are 6 multiples of 6, 3 of 10 and 2 of 15, so the count is 37 − 11 = 26. But only 9 numbers are divisible by none of 2, 3 and 5 (1, 7, 11, 13, 17, 19, 23, 29 and 31), so the answer is 27: one number was lost.

A 6 by 6 table of the numbers 1 to 36: the 27 numbers divisible by 2, 3 or 5 are shaded grey with a small counter 1 in the corner, except 30, which is red with counter 0; the numbers 1, 7, 11, 13, 17, 19, 23, 29 and 31 are white with no counter.

Fig. 2. After adding the multiples of 2, 3 and 5 and subtracting the overlaps of two, every shaded number is counted once, except 30, which is not counted at all.

Look at 30 in Fig. 2. It was added three times, as a multiple of 2, 3 and 5, and subtracted three times, as a multiple of 6, 10 and 15, so it is counted 0 times.

So the numbers in all three sets must be added back once. They are the multiples of 30, and 36 / 30 = 1: 37 − 11 + 1 = 27.

General rule

With more divisors this repeats one level deeper, so write down every term at once. For each non-empty group of the sets, count the elements that are in all of them. A group of odd size adds its count, and a group of even size subtracts it. sets give 2^k - 1 groups.

This is the inclusion–exclusion principle. For divisors, the numbers in all of a group's sets are the multiples of the group's least common multiple (lcm), which for different primes is their product. For 4 and 6 the lcm is 12, not 24: 12 is divisible by both, but counting multiples of 24 would skip it.

A 6 by 6 table of the numbers 1 to 36 with a counter in each cell divisible by 2, 3 or 5; step by step the multiples of 2, 3, 5, 6, 10, 15 and 30 are added or subtracted, 30 is outlined, and the total goes 18, 30, 37, 31, 28, 26, 27.

No group yet. Every counter is 0. Total 0.

1/8

Fig. 3. Step through the 7 terms with the buttons or the arrow keys. Blue terms add, red terms subtract.

Every shaded number ends at 1, so 27 numbers are divisible by 2, 3 or 5, and 36 − 27 by none.

Why the signs alternate

A number in exactly of the sets is counted only by the groups of those divisors: added times, subtracted C(j, 2) times, and so on (binomial coefficients). Match each group of the divisors with the group you get by adding or removing the first one.

For 2, 3 and 5 the matches are the empty group with {2}, {3} with {2, 3}, {5} with {2, 5}, and {3, 5} with {2, 3, 5}. Each match has one odd and one even group, so without the empty group the odd groups win by one, and every number is counted once.

Use the principle when a question asks for the objects that meet at least one of conditions, or none of them, the objects meeting all conditions of a group are easy to count, and is at most about 20.

Implementation

A group is a bitmask: bit i of mask says whether a[i] is in the group, and __builtin_popcount(mask) is its size. The variable step holds the lcm of the group, built one member at a time as step / gcd(step, a[i]) * a[i].

  1. Choose a group: mask from 1 to 2^k - 1.

  2. Lcm: step, the lcm of the group; stop once it passes n.

  3. Count: n / step multiples up to n.

  4. Sign: odd size adds, even size subtracts.

The input is n and k, then the k positive divisors. The bitmask implementation assumes k <= 20 and 0 <= n <= 10^18. Its signed accumulator also requires every intermediate partial sum to fit in long long; for unrestricted inputs use a wider accumulator such as __int128 on supporting compilers.

36 3
2 3 5
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;

// how many numbers from 1 to n are divisible by at least one of a[0], ..., a[k-1]
long long count(long long n, const vector<long long>& a) {
    int k = a.size();
    long long total = 0;
    for (int mask = 1; mask < (1 << k); mask++) {               // 1. choose a group
        long long step = 1;                                     // 2. lcm of the group
        for (int i = 0; i < k; i++)
            if (mask >> i & 1) {
                long long g = gcd(step, a[i]);
                if (step / g > n / a[i]) { step = n + 1; break; }   // bigger than n: no multiples
                step = step / g * a[i];
            }
        long long cnt = n / step;                               // 3. count the multiples
        if (__builtin_popcount(mask) % 2 == 1) total += cnt;    // 4. odd size adds
        else total -= cnt;                                      //    even size subtracts
    }
    return total;
}

int main() {
    long long n;
    int k;
    cin >> n >> k;
    vector<long long> a(k);
    for (auto& x : a) cin >> x;
    cout << count(n, a) << "\n";
}

The loop visits 2^k-1 non-empty subsets and checks at most members of each, so there are O(k2^k) member checks and gcd operations (each gcd takes logarithmic time in its arguments). Extra memory is including the divisor array.

Numbers in a range

For the numbers from L to R, count up to R and remove those up to L - 1:

long long in_range = count(R, a) - count(L - 1, a);

Numbers coprime to m

A number shares a factor with m exactly when one of the distinct primes of m divides it. So find these primes by trial division, in O(\sqrt{m}), and take the complement. A number up to 10^9 has at most 9 distinct primes, so at most 511 groups.

vector<long long> primes;                 // distinct primes of m (m is changed)
for (long long d = 2; d * d <= m; d++)
    if (m % d == 0) {
        primes.push_back(d);
        while (m % d == 0) m /= d;
    }
if (m > 1) primes.push_back(m);
long long coprime = n - count(n, primes);

Derangements

A derangement puts letters into their envelopes so that no letter is in its own envelope. Let set hold the arrangements with letter in its own envelope, apply the same rule to these sets, and subtract the result from all arrangements.

Any of the sets meet in (n - i)! arrangements, and there are C(n, i) groups of size , so the derangements number D(n) = n! - C(n, 1) \cdot (n - 1)! + C(n, 2) \cdot (n - 2)! - \dots For n = 4: 24 − 24 + 12 − 4 + 1 = 9.

Each term C(n, i) \cdot (n - i)! equals , and this gives a shorter rule, D(n) = n \cdot D(n - 1) + (-1)^n. From D(3) = 2 it gives D(4) = 4 \cdot 2 + 1 = 9.

vector<long long> D(n + 1);
D[0] = 1;                                          // one way to arrange nothing
for (int i = 1; i <= n; i++)
    D[i] = i * D[i - 1] + (i % 2 == 0 ? 1 : -1);   // exact up to n = 20

Common mistakes

Similar techniques

  • Euler's totient counts the numbers up to coprime to itself with a product formula; for any other bound, use inclusion–exclusion.

  • The sieve of Eratosthenes marks multiples in an array, for up to about 10^7; inclusion–exclusion reaches 10^{18}, but its time doubles with each divisor.

  • Stars and bars with an upper limit per box uses inclusion–exclusion over the boxes that are over their limit, with binomial coefficients as terms.

  • Binary search on the answer finds the -th number divisible by one of the divisors, with inclusion–exclusion counting up to each guess.

Practice

Bu səhifə faydalı oldumu?