Ride-hailing app~25 min2s · 256 MBtarget O(n log log n) time, O(n) spaceclassic twin: lc-204number-theory
A ride app numbers the pick-up spots along a long street from 2 up to n. A spot is staffed when its number is a prime number, that is, a number above 1 that only 1 and itself divide.
The operations team wants to find the longest stretch with no staffed spot between two staffed spots. Your team lead asks: "What is the largest difference between two neighbouring staffed spots, and where does it start?"
Write widest_gap(n).
n is the last spot number. The spots are 2, 3, ..., n.[0, 0].Input: n = 30
Output: [6, 23]The staffed spots up to 30 are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29. The table lists each pair of neighbours and keeps the largest gap so far.
| Previous prime | Next prime | Gap | Largest gap so far |
|---|---|---|---|
| 2 | 3 | 1 | 1 |
| 3 | 5 | 2 | 2 |
| 5 | 7 | 2 | 2 |
| 7 | 11 | 4 | 4 |
| 11 | 13 | 2 | 4 |
| 13 | 17 | 4 | 4 |
| 17 | 19 | 2 | 4 |
| 19 | 23 | 4 | 4 |
| 23 | 29 | 6 | 6 |
The largest gap is 6, between 23 and 29, and it starts at 23.
Input: n = 2
Output: [0, 0]Only the spot 2 is staffed, so there is no pair and no gap.
Input: n = 100
Output: [8, 89]The gap from 89 to 97 is 8, and it is the largest gap up to 100.
1 ≤ n ≤ 20,000,000Testing each number by trial division costs up to about the square root of the number, so it takes about 44,721,359,549 steps for 20,000,000 numbers. Crossing off multiples of each prime, the sieve of Eratosthenes, costs about n × log(log n), roughly 5 × 10^7 steps. One more pass over the flags then finds the gaps.