Inclusion-exclusion counts how many numbers from 1 to N are divisible by at least one of several divisors, without looking at each number. Your program applies it to up to four divisors.
What to build
A program that counts the numbers from 1 to N divisible by at least one of the given divisors.
Requirements
- Read N, then a line with the divisors.
- Print the count of numbers x with 1 ≤ x ≤ N that are divisible by at least one of the divisors.
- Use inclusion-exclusion: add the counts for single divisors, subtract those for pairs (using the lcm), add those for triples, and so on.
Input
Line 1: N. Line 2: 1 to 4 divisors.
Output
One whole number.
Constraints
1 ≤ N ≤ 10 to the power 9; divisors from 1 to 100.
Example
Input:
100
2 3 5
Output:
74
Why it works
The multiples of d among 1 to N number N // d, and the numbers divisible by several divisors at once are the multiples of their lcm. Counting singles adds those in several sets more than once, so each overlap is subtracted, and the triple overlaps added back, with alternating signs, which is the inclusion-exclusion rule.
Examples
100 2 3 5
74
100 3 5
47
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For a set of divisors, the numbers divisible by all of them are the multiples of their lcm: N // lcm.
Hint 2
Use math.lcm and loop over the non-empty subsets of the divisors (itertools.combinations).
Hint 3
Add the counts for subsets of odd size and subtract them for even size.
Solution
Show one correct solution (try it yourself first)
from itertools import combinations
from math import lcm
n = int(input())
divs = list(map(int, input().split()))
total = 0
for size in range(1, len(divs) + 1):
for group in combinations(divs, size):
total += (-1) ** (size + 1) * (n // lcm(*group))
print(total)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step