Given an integer n
, return the number of prime numbers that are strictly less than n
.
n
?
1 <= n <= 5 * 10^6
based on typical constraints.n <= 2
?
n <= 2
.n
.To count prime numbers less than n
, an efficient algorithm is needed: the Sieve of Eratosthenes.
is_prime
of size n
and initialize all entries to True
. This array indicates whether each number is a prime.is_prime[0]
and is_prime[1]
to False
since 0 and 1 are not primes.p
starting from 2, if p
is a prime, mark all multiples of p
as False
(not prime).p^2 >= n
.True
values in is_prime
array will give the count of prime numbers less than n
.def countPrimes(n: int) -> int:
if n <= 2:
return 0
# Initialize a list to track prime numbers
is_prime = [True] * n
is_prime[0] = is_prime[1] = False # 0 and 1 are not prime numbers
# Apply Sieve of Eratosthenes
p = 2
while p * p < n:
if is_prime[p]:
# Mark all multiples of p as False
for multiple in range(p * p, n, p):
is_prime[multiple] = False
p += 1
# Count all prime numbers
return sum(is_prime)
# Example usage:
n = 10
print(countPrimes(n)) # Output is 4 (primes: 2, 3, 5, 7)
is_prime
array.This algorithm efficiently counts the number of primes less than a given number n
in an optimal manner for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?