Example 1
- Input
- n = 10
- Output
- 4
Exactly 2, 3, 5 and 7 are prime below 10. The values 4, 6, 8 and 9 have smaller divisors, and 1 is not prime.
Count the prime numbers strictly below n. A prime is an integer greater than one whose only positive divisors are one and itself.
Given a nonnegative integer n, return the number of primes strictly less than n. A prime has exactly two positive divisors: 1 and itself.
The upper endpoint is excluded: for n = 2, the answer is 0; for n = 3, the answer is 1 because only 2 qualifies.
0 <= n <= 5 * 10^6.Exactly 2, 3, 5 and 7 are prime below 10. The values 4, 6, 8 and 9 have smaller divisors, and 1 is not prime.
There are no positive prime candidates below zero; return before allocating a sieve.
The only nonnegative candidate below 1 is 0, which is not prime.
The prime 2 is included, but 3 itself is excluded. This distinguishes strict from inclusive counting.
The primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 and 47. Marking 49 when processing 7 is essential.
For n = 10, the candidates are 2 through 9. Testing divisors identifies 2, 3, 5, 7 as prime. But each composite has a smaller prime factor: 6 can be rejected when processing 2, without testing it separately. A sieve records these rejections for all candidates together. When 3 is reached, its smaller multiples have already been handled by 2, so its first new multiple is 9.
Reveal Trial Division: intuition, complexity, and code
When many queries share a bounded integer domain, preprocess facts across that domain instead of repeating a search for each value. A prime sieve discovers one factor and eliminates all its relevant multiples.