progress

~/problems / Number theory / Primes, divisors and GCD

Festival lanterns blinking together

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

Lantern i flashes on every multiple of periods[i]. For the fireworks, the organisers want to know on how many days in 1..days every lantern flashes at once.

Write together_days(periods: list[int], days: int) -> int.

together_days([4, 6], 30)        # 2    (days 12 and 24)
together_days([3, 5, 7], 100)    # 0    (the first common day is 105)
together_days([2, 2, 8], 16)     # 2    (days 8 and 16)
together_days([1], 5)            # 5

All lanterns flash together on the multiples of the periods' least common multiple. Fold it in one period at a time: lcm(a, b) = a // gcd(a, b) * b. math.gcd is fine.

Up to 10^5 periods (each up to 10^9); days up to 10^18.

⭐ Bonus: speed tests with 10^5 lanterns earn a star if you stop as soon as the running LCM passes days (the answer is then 0). With coprime periods the full LCM has millions of digits.

Show hint

L = 1; for each p: L = L // gcd(L, p) * p, and if L > days: return 0. Finally return days // L.

Topic: Primes, divisors and GCD. Sieve, trial division to sqrt(n), Euclid's algorithm.

0:00
Ctrl ' run · Ctrl ↵ submit
esc