Two Sets
∣A∪B∣=∣A∣+∣B∣−∣A∩B∣
We subtract ∣A∩B∣ because elements in both sets were counted twice.
Three Sets
∣A∪B∪C∣=∣A∣+∣B∣+∣C∣−∣A∩B∣−∣A∩C∣−∣B∩C∣+∣A∩B∩C∣
General Formula
For n sets A1,A2,…,An:
∣⋃i=1nAi∣=∑i∣Ai∣−∑i<j∣Ai∩Aj∣+∑i<j<k∣Ai∩Aj∩Ak∣−⋯+(−1)n+1∣A1∩A2∩⋯∩An∣
Or more compactly:
∣⋃i=1nAi∣=∑∅=S⊆{1,…,n}(−1)∣S∣+1⋂i∈SAi
Complement Form
For counting elements NOT in any set:
A1∪A2∪⋯∪An=∣U∣−∣⋃i=1nAi∣
This is useful for "none of the above" counting.
Examples
Integers Divisible by 2, 3, or 5
How many integers from 1 to 1000 are divisible by 2, 3, or 5?
Let A2,A3,A5 be sets of multiples.
∣A2∣=⌊1000/2⌋=500
∣A3∣=⌊1000/3⌋=333
∣A5∣=⌊1000/5⌋=200
∣A2∩A3∣=⌊1000/6⌋=166
∣A2∩A5∣=⌊1000/10⌋=100
∣A3∩A5∣=⌊1000/15⌋=66
∣A2∩A3∩A5∣=⌊1000/30⌋=33
∣A2∪A3∪A5∣=500+333+200−166−100−66+33=734
Euler's Totient Function
ϕ(n) = count of integers from 1 to n that are coprime to n.
For n=p1a1p2a2⋯pkak:
ϕ(n)=n∏p∣n(1−p1)=n(1−p11)(1−p21)⋯(1−pk1)
Example: ϕ(12)=ϕ(22⋅3)=12⋅(1−1/2)(1−1/3)=12⋅21⋅32=4
Derangements
A derangement is a permutation where no element is in its original position.
Let Ai = permutations where element i is fixed.
The number of derangements of n elements:
Dn=n!−∣A1∪A2∪⋯∪An∣
Using inclusion-exclusion:
Dn=n!∑k=0nk!(−1)k=n!(1−1+2!1−3!1+⋯+n!(−1)n)
| n | Dn | Formula |
|---|
| 0 | 1 | — |
| 1 | 0 | 1−1 |
| 2 | 1 | 2−2+0 |
| 3 | 2 | 6−6+3−1 |
| 4 | 9 | 24−24+12−4+1 |
| 5 | 44 | — |
As n→∞: Dn/n!→1/e≈0.368
Surjective Functions
The number of surjective (onto) functions from an n-set to a k-set:
S(n,k)⋅k!=∑j=0k(−1)j(jk)(k−j)n
where S(n,k) is the Stirling number of the second kind.
Derivation: Let Ai = functions missing element i in the range.
Surjections = Total functions - (functions missing at least one element)
Sieve of Eratosthenes
Primes up to n: Start with all numbers, sieve out multiples.
Using inclusion-exclusion with prime divisors gives the count of numbers with no small prime factors.
Hat Check Problem
n people check hats, hats returned randomly. Probability no one gets own hat?
P=n!Dn=∑k=0nk!(−1)k≈e1≈0.368
Counting with "At Least" Conditions
Example: Distribute 10 identical balls into 4 distinct boxes, each box has at least 1 ball.
First give each box 1 ball (4 balls used). Distribute remaining 6:
(4−16+4−1)=(39)=84
Alternatively, using inclusion-exclusion on "box i is empty":
(313)−4(312)+(24)(311)−(34)(310)+(44)(39)
Both methods give 84.