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.

Approach

Let S_x be the integers in [1, n] divisible by x. The answer is |S_a \cup S_b \cup S_c \cup S_d|.

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 \mathrm{lcm}(T), and there are \lfloor n / \mathrm{lcm}(T) \rfloor 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 \mathrm{lcm}(T) > n, that term is 0. In C++ the raw lcm of four values up to 10^9 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)

Comments

There are no comments at the moment.