Editorial for Four Multiples
Use this editorial only when stuck, and do not copy-paste code from it.
Please be respectful to the problem author and editorialist. Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let Sx be the integers in [1,n] divisible by x. The answer is ∣Sa∪Sb∪Sc∪Sd∣.
Four-set inclusion-exclusion expands this into the 15 nonempty subsets of {a,b,c,d}. For a subset T, the integers divisible by every modulus in T are exactly those divisible by lcm(T), and there are ⌊n/lcm(T)⌋ of them. Add the term if ∣T∣ is odd and subtract if ∣T∣ is even.
Loop over bitmasks 1..15 rather than writing out 15 terms by hand. Hardcoding the terms works for four sets, but it is easy to miss a sign or an lcm, and the mask loop is the same code you would use for more sets.
If lcm(T)>n, that term is 0. In C++ the raw lcm of four values up to 109 may not fit in a 64-bit integer; stop early when the running lcm already exceeds n. Time is O(1).
Solution (Python)
from math import gcd
n, a, b, c, d = map(int, input().split())
mods = [a, b, c, d]
ans = 0
for mask in range(1, 16):
cur = 1
bits = 0
too_big = False
for i in range(4):
if mask & (1 << i):
bits += 1
g = gcd(cur, mods[i])
nxt = cur // g * mods[i]
if nxt > n:
too_big = True
break
cur = nxt
if too_big:
continue
term = n // cur
if bits % 2:
ans += term
else:
ans -= term
print(ans)
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.