Editorial for Four Multiples
Remember to use this editorial only when stuck, and not to 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.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let be the integers in
divisible by
. The answer is
.
Four-set inclusion-exclusion expands this into the nonempty subsets of
.
For a subset
, the integers divisible by every modulus in
are exactly those divisible by
, and there are
of them. Add the term if
is odd and subtract if
is even.
Loop over bitmasks rather than writing out
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 , that term is
. In C++ the raw lcm of four values up to
may
not fit in a 64-bit integer; stop early when the running lcm already exceeds
. Time is
.
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)
Comments