The Inclusion-Exclusion Principle and Euler's Totient Function
TL;DR
I wanted to organize my understanding of the inclusion-exclusion principle and Euler's totient function, so I'm writing these notes. For precise information, please refer to the references section.
Consider an arbitrary element x belonging to ∣A1∪A2∪A3...An−1∪An∣. On the left side, element x is counted exactly once.
Now, on the right side, considering the plus and minus signs, we count how many times element x is counted in ∣Aj1∩Aj2...∩Aji∣. Let k be the number of sets containing x, and let the sets containing x be Ai(i∈k). We ignore sets that don't contain x since they contribute nothing to the count.
The number of times x is counted across single sets Ai(i∈k) is kC1. The number of times it's counted in pairwise intersections Ai∩Aj(i,j∈k) is kC2. Similarly, the number of combinations of r intersections of sets containing x where x is counted is kCr. Taking the plus and minus signs into account:
r=1∑k(−1)r−1kCr
On the other hand, by the binomial theorem:
0=(1−1)k=r=0∑kkCr(−1)r=1−r=1∑kkCr(−1)r−1
Therefore, the count of any element x is equal on both sides. Hence, the principle holds.
Implementation
This is what I wanted to write down.
It can be implemented using bit exhaustive search.
Let's consider multiples of 2, 3, 5 that are at most 100.
fnmain(){let nums =vec![2,3,5];letmut counter =0;for bit in0..1<< nums.len(){// Count the number of 1s in binary representationlet popcount = bit.count_ones();letmut mul =1;for i in0..nums.len(){if bit &1<< nums.len(){ mul *= nums[i]}}if mul ==1{continue;}if popcount %2==1{ counter +=100/ mul;}else{ counter -=100/ mul;}}println!("{}", counter)}
Since divisibility can be determined, prime factorization lets us count coprime numbers as well.
Euler's Totient Function: Count of Natural Numbers up to N that are Coprime to N
For any natural number n, the number of natural numbers less than or equal to n that are coprime to n is written as ϕ(n).
Given the prime factors pi of n:
ϕ(n)=ni=1∏k(1−pi1)
Proof Using the Inclusion-Exclusion Principle
The approach seems correct, but I'm not sure what happened with the final algebraic transformation.
For any x(1≤x≤k), let ∣Ai∣ be the set of natural numbers that are multiples of the prime pi and at most n. Then ∣Ai∣=pin (e.g., the number of multiples of 2 that are at most 100 is 100/2).