Music streaming app~20 min2s · 256 MBtarget O(n log log n) time, O(n) spaceclassic twin: lc-204number-theory
A live-stream app numbers its viewers 1, 2, 3, ... in the order they join. For a special event, every viewer whose number is prime gets a lucky badge. A prime is a whole number above 1 that only 1 and itself divide.
Your team lead asks: "How many badges went to the viewers numbered from low to high?" The event can have 10,000,000 viewers.
Write count_primes_in_range(low, high).
low and high are viewer numbers, with low ≤ high. Both ends are included.p have low ≤ p ≤ high.Input: low = 10, high = 30
Output: 6Cross off numbers instead of testing each one. List 2 to 30. Take the smallest number not crossed off, p, and cross off its multiples from p × p. Stop when p × p is above 30.
| p | Crossed off | Numbers still standing |
|---|---|---|
| 2 | 4, 6, 8, ..., 30 | 2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29 |
| 3 | 9, 15, 21, 27 | 2, 3, 5, 7, 11, 13, 17, 19, 23, 25, 29 |
| 5 | 25 | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 |
| 7 | none: 7 × 7 is 49, above 30 | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 |
From 10 to 30, the numbers still standing are 11, 13, 17, 19, 23 and 29: six primes.
Input: low = 1, high = 10
Output: 4The primes up to 10 are 2, 3, 5 and 7. The number 1 is not prime.
Input: low = 24, high = 28
Output: 024, 25, 26, 27 and 28 each have a divisor between 2 and half their size.
1 ≤ low ≤ high ≤ 10,000,000Testing each number alone costs up to about 3,162 divisions for a prime near 10,000,000. There are 664,579 primes up to that limit, so the whole range takes about 1.7 billion divisions. A table with one flag for each number up to 10,000,000 needs only about 10 MB. You build it once and share it between all the numbers.