Editorial for Four Multiples


Approach

Let SxS_x be the integers in [1,n][1, n] divisible by xx. The answer is ∣Sa∪Sb∪Sc∪Sd∣|S_a \cup S_b \cup S_c \cup S_d|.

Four-set inclusion-exclusion expands this into the 1515 nonempty subsets of {a,b,c,d}\{a, b, c, d\}. For a subset TT, the integers divisible by every modulus in TT are exactly those divisible by lcm(T)\mathrm{lcm}(T), and there are ⌊n/lcm(T)⌋\lfloor n / \mathrm{lcm}(T) \rfloor of them. Add the term if ∣T∣|T| is odd and subtract if ∣T∣|T| is even.

Loop over bitmasks 1..151..15 rather than writing out 1515 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\mathrm{lcm}(T) > n, that term is 00. In C++ the raw lcm of four values up to 10910^9 may not fit in a 64-bit integer; stop early when the running lcm already exceeds nn. Time is O(1)O(1).

Solution (Python)

Code 1
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.