Problem Description
Given an integer n, return the number of prime numbers that are strictly less than n. For example, when n = 10 there are 4 prime numbers less than 10: 2, 3, 5, and 7.
Key Insights
- The problem can be efficiently solved using the Sieve of Eratosthenes.
- Only numbers less than n are considered.
- Iterating only up to the square root of n will mark all non-prime numbers effectively.
- An auxiliary boolean array can represent whether each number is prime.
Space and Time Complexity
Time Complexity: O(n log log n)
Space Complexity: O(n)
Solution
The Sieve of Eratosthenes algorithm is used to solve this problem. We create a boolean array of size n where each index initially assumes the number is prime. We then mark 0 and 1 as non-prime. For each number p starting from 2 up to the square root of n, if p is still marked as prime, we mark all multiples of p (starting at p*p) as non-prime. Finally, the count of true values in the boolean array gives the number of primes less than n.