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?- A. 733333334 36 36
- B. 733333334 40 36
- C. 733333333 36 36
- 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
- Problem: Compute C(n, r) mod a SMALL prime p = 7 when n ≥ p: Lucas' theorem versus factorials with Fermat inverses. python p = 7 fact =…
- Problem: Count ways to climb n stairs with steps of 1 or 3, modulo 10⁹ + 7, using a 3 × 3 matrix power so that n up to 10¹⁸ is fine…
- Problem: Peak number of simultaneous bookings with a sweep line. In the first call intervals are CLOSED [s, e] (a booking ending at 3 and…
- Problem: Total length covered by a set of intervals, and the length covered by EXACTLY one interval, using coordinate compression and a…
- Problem: Warehouses at positions a with daily shipments w; choose a hub position x minimising Σ wᵢ·|aᵢ − x|. Compare the weighted median…
- Problem: Minimum cuts to split a string into palindromes: interval DP (pal table + cut array) versus the greedy 'always take the longest…