Given an integer n
, return the number of prime numbers that are strictly less than n
.
Example 1:
Input: n = 10 Output: 4 Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
Example 2:
Input: n = 0 Output: 0
Example 3:
Input: n = 1 Output: 0
Constraints:
0 <= n <= 5 * 106
This problem asks to find the number of prime numbers less than a given integer n
. The most efficient approach is using the Sieve of Eratosthenes algorithm.
Algorithm (Sieve of Eratosthenes):
Initialization: Create a boolean array primes
of size n
, initially filled with True
. primes[i]
will be True
if i
is prime, and False
otherwise. We don't need to consider 0 and 1 as they are not primes.
Iteration: Iterate from i = 2
up to sqrt(n)
. We only need to iterate up to the square root because if a number x
has a divisor greater than sqrt(x)
, it must also have a divisor smaller than sqrt(x)
.
Marking Non-Primes: If primes[i]
is True
(meaning i
is prime), mark all multiples of i
as False
(they are not prime). Start marking from i * i
because smaller multiples would have already been marked by previous iterations.
Counting Primes: After the iteration, count the number of True
values in the primes
array (excluding indices 0 and 1). This count represents the number of primes less than n
.
Time Complexity: O(n log log n). The outer loop iterates up to sqrt(n)
. The inner loop iterates through multiples of i
, and the total number of iterations in the inner loop across all outer iterations is approximately proportional to n log log n
which is significantly less than O(n).
Space Complexity: O(n). This is due to the boolean array primes
of size n
.
Code Explanation (Python):
class Solution:
def countPrimes(self, n: int) -> int:
primes = [True] * n # Initialize boolean array
ans = 0 # Initialize prime count
for i in range(2, int(math.sqrt(n)) + 1): # Iterate up to sqrt(n)
if primes[i]: # If i is prime
ans += 1 # Increment prime count
for j in range(i * i, n, i): # Mark multiples of i as non-prime
primes[j] = False
#Count primes from 2 to sqrt(n) and add primes between sqrt(n) and n if any.
for i in range(int(math.sqrt(n)) + 1,n):
if primes[i]:
ans+=1
return ans
The code in other languages (Java, C++, Go, JavaScript, C#) follows the same algorithm and logic. They differ only in syntax and specific library functions used. The core idea remains the efficient Sieve of Eratosthenes.
Example:
Let's say n = 10
.
primes
is initialized as [True, True, True, True, True, True, True, True, True, True]
i = 2
to 3
(sqrt(10) ≈ 3.16
).i = 2
, multiples of 2 (4, 6, 8) are marked as False
.i = 3
, multiples of 3 (9) are marked as False
.primes
becomes [False, False, True, True, False, True, False, True, False, False]
.True
values (excluding indices 0 and 1) is 4 (2, 3, 5, 7), which is the correct answer.