Online store~15 min2s · 256 MBtarget O(n log log n) time, O(n) spacenumber-theory
A store numbers the bins of one long shelf row from 1 to bins. The picking robots treat two bins as a twin pair when both of their numbers are prime and the two numbers differ by exactly 2. A prime is a whole number above 1 that only 1 and itself divide.
Your team lead asks: how many twin pairs does the row have? A pair needs both of its bins to exist on the row.
Write count_twin_bins(bins).
1 to bins.p and p + 2, with p + 2 ≤ bins, where both p and p + 2 are prime.Input: bins = 30
Output: 4Mark the primes with a sieve: list 1 to 30, and for each prime p, cross off its multiples from p x p onwards. The primes up to 30 are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.
Now look at every p with both p and p + 2 still standing, and p + 2 ≤ 30.
p |
p + 2 |
Both prime? |
|---|---|---|
| 3 | 5 | yes |
| 5 | 7 | yes |
| 11 | 13 | yes |
| 17 | 19 | yes |
| 29 | 31 | no: 31 is not on the row |
The answer is 4. The pair 29 and 31 does not count, because bin 31 does not exist.
Input: bins = 4
Output: 0The primes are 2 and 3. The pair 3 and 5 needs bin 5, which does not exist.
Input: bins = 7
Output: 2The pairs are 3 and 5, and 5 and 7. Bin 5 is in both pairs, and each pair counts once.
1 ≤ bins ≤ 10^7Testing each number by trying divisors up to its square root costs about 10^9 steps in all for 10^7 numbers, too slow for 2 seconds.
A sieve crosses off multiples and handles all the numbers together, in about 3 x 10^7 steps. It needs a table of 10^7 flags, which fits in 256 MB. The answer is below 10^6, so a 32-bit integer holds it.