#204
Count Primes
MediumArrayMathEnumerationNumber TheorySieve of EratosthenesArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log log n)Space O(n)
The Sieve of Eratosthenes is an efficient algorithm to find all primes up to a given limit. It works by iteratively marking the multiples of each prime number starting from 2.
⚙️
Algorithm
4 steps- 1Step 1: Create a boolean array 'is_prime' of size n initialized to True.
- 2Step 2: Set is_prime[0] and is_prime[1] to False (0 and 1 are not primes).
- 3Step 3: Loop from 2 to the square root of n. For each number, if it is still marked as prime, mark all its multiples as not prime.
- 4Step 4: Count the number of True values in 'is_prime' array, which represents the prime numbers.
solution.py12 lines
1# Full working Python code
2
3def countPrimes(n):
4 if n < 3:
5 return 0
6 is_prime = [True] * n
7 is_prime[0], is_prime[1] = False, False
8 for i in range(2, int(n**0.5) + 1):
9 if is_prime[i]:
10 for j in range(i * i, n, i):
11 is_prime[j] = False
12 return sum(is_prime)ℹ
Complexity note: The time complexity is O(n log log n) due to the Sieve of Eratosthenes marking multiples, which is much faster than the brute force method. The space complexity is O(n) for storing the boolean array.
- 1Understanding prime numbers is crucial for optimizing algorithms.
- 2The Sieve of Eratosthenes is a classic example of an efficient algorithm that reduces unnecessary checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.