Count Primes
Problem
Given an integer n
, return the number of prime numbers that are strictly less than n
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Naive
This solution exceeds time limit.
Code
|
|
Method 2 - Using Sieve of Eratosthenes
This solution is the implementation of Sieve of Eratosthenes Algorithm. This is a well-known and efficient algorithm for finding all prime numbers up to a specified integer.
Sieve of Eratosthenes Algorithm
- Create a boolean array of size ( n ) and initialize all entries as true. Entries at index positions which are non-prime will be marked as false.
- Set the values for 0 and 1 as false (since 0 and 1 are not prime numbers).
- For each number ( p ) from 2 to ( \sqrt{n} ):
- If ( p ) is still true in the array, it is a prime number.
- Mark all multiples of ( p ) (starting from ( p \times p )) as false.
- Count the number of true values left in the array. These correspond to the prime numbers strictly less than ( n ).
Code
|
|
Complexity
- ⏰ Time complexity:
O(n log(log(n)))
- 🧺 Space complexity:
O(n)