Ad platform~18 min2s · 256 MBtarget O(n log V + V) time, O(V) spacenumber-theory
You work on an ad platform. Each campaign restarts its creative every cycles[i] days. All campaigns start together today, and the team wants to know when they all start together again.
Your team lead asks: "After how many days do all campaigns restart on the same day?" That day count can be enormous, so report it modulo 1,000,000,007. A request holds up to 100,000 campaigns, with cycles up to 1,000,000 days.
Write lcm_mod(cycles).
cycles[i] is the length of the cycle of campaign i, in days.cycles[i] divides: their least common multiple.Input: cycles = [4, 6, 10]
Output: 60Write each cycle as a product of primes: 4 = 2², 6 = 2 × 3, 10 = 2 × 5. The least common multiple takes the highest power of each prime that appears.
| Prime | Exponents in 4, 6 and 10 | Highest | Contribution |
|---|---|---|---|
| 2 | 2, 1, 1 | 2 | 4 |
| 3 | 0, 1, 0 | 1 | 3 |
| 5 | 0, 0, 1 | 1 | 5 |
The product is 4 × 3 × 5 = 60.
Input: cycles = [7]
Output: 7One campaign restarts after its own cycle.
Input: cycles = [1000000, 999999, 1000000]
Output: 998993007The true least common multiple is 999,999,000,000. Its remainder modulo 1,000,000,007 is 998993007.
1 ≤ len(cycles) ≤ 100,0001 ≤ cycles[i] ≤ 1,000,000The least common multiple of many numbers up to 1,000,000 can have hundreds of thousands of digits. The 78,498 primes up to 1,000,000 give 433,637 digits, and the numbers 1 to 100,000 alone give 43,452. You cannot keep it exactly, and you cannot apply the modulus while you fold, because the fold divides. A table of prime factors up to 1,000,000 is cheap, and it works with small numbers only.