Math Fundamentals18 sections · 814 units
Open in Course

Ugly Number III - Inclusion-Exclusion

Counting with three sets

Count numbers ≤ x divisible by a, b, or c. Use inclusion-exclusion: count = |A| + |B| + |C| - |A∩B| - |A∩C| - |B∩C| + |A∩B∩C|.

|A| = x/a, |B| = x/b, |C| = x/c. |A∩B| = x/lcm(a,b). |A∩C| = x/lcm(a,c). |B∩C| = x/lcm(b,c). |A∩B∩C| = x/lcm(a,b,c).

Formula: count(x) = x/a + x/b + x/c - x/lcm(a,b) - x/lcm(a,c) - x/lcm(b,c) + x/lcm(a,b,c).