Data Structures & AlgorithmsVery hardProduct company OA

Problem: Count integers in [1, N] divisible by at least one of the given numbers using inclusion–exclusion with LCMs (N up to 10⁹, so no loop over N).

Problem: Count integers in [1, N] divisible by at least one of the given numbers using inclusion–exclusion with LCMs (N up to 10⁹, so no loop over N).
from math import gcd
from itertools import combinations
def count_div(N, ps):
    total = 0
    for r in range(1, len(ps) + 1):
        for c in combinations(ps, r):
            l = 1
            for x in c: l = l * x // gcd(l, x)
            total += (-1) ** (r + 1) * (N // l)
    return total
print(count_div(10**9, [2, 3, 5]), count_div(100, [4, 6, 10]), sum(1 for x in range(1, 101) if x % 4 == 0 or x % 6 == 0 or x % 10 == 0))
What is printed?
  1. A. 733333334 36 36
  2. B. 733333334 40 36
  3. C. 733333333 36 36
  4. D. 1033333333 40 40

Correct answer: A. 733333334 36 36

Add counts for single divisors, subtract pairs, add triples, each using the LCM. For 2, 3, 5: 5·10⁸ + 333333333 + 2·10⁸ − 166666666 − 10⁸ − 66666666 + 33333333 = 733333334. For 4, 6, 10 the trap is using products instead of LCMs: lcm(4, 6) = 12, lcm(4, 10) = 20, lcm(6, 10) = 30, lcm of all = 60 → 25 + 16 + 10 − 8 − 5 − 3 + 1 = 36, matching brute force; products (24, 40, 60, 240) give 40. O(2^k) terms.

More Coding Interview Problems questions

Exams that ask this topic