Maps app~35 min2s · 256 MBtarget O(top log top + n) time, O(top) spacenumber-theory
You work on a maps app that plans bus timetables. Each route runs a loop that takes loops[i] minutes, and every route leaves the depot at minute 0. Two routes with loop lengths a and b are in different rhythms when a and b have no common factor above 1. Then their buses meet at the depot only every a × b minutes.
Your team lead asks: "How many pairs of routes have no shared rhythm?" A request holds up to 100,000 routes, with loops up to 200,000 minutes.
Write count_coprime_pairs(loops).
loops[i] is the loop length of route i, in minutes.i < j. Routes with equal loop lengths are still different routes.Input: loops = [6, 10, 15, 7]
Output: 3| Pair | Loops | Common divisor | Counts |
|---|---|---|---|
| 0, 1 | 6 and 10 | 2 | no |
| 0, 2 | 6 and 15 | 3 | no |
| 0, 3 | 6 and 7 | 1 | yes |
| 1, 2 | 10 and 15 | 5 | no |
| 1, 3 | 10 and 7 | 1 | yes |
| 2, 3 | 15 and 7 | 1 | yes |
Input: loops = [1, 1, 1]
Output: 3Every pair of routes with loop length 1 has no common factor above 1, so all 3 pairs count.
Input: loops = [12, 35, 18, 25, 49]
Output: 7Only the pairs (12, 18), (35, 25) and (35, 49) share a factor, so 10 - 3 = 7 pairs count.
1 ≤ len(loops) ≤ 100,0001 ≤ loops[i] ≤ 200,000Testing every pair with a gcd takes n × (n - 1) / 2 tests, which is 4,999,950,000 for 100,000 routes. The loop lengths are at most 200,000, so there are only 200,000 possible values. Counting how many routes have a loop that is a multiple of d, for every d, takes about 1,641,000 steps in total.