Leetcode Problem 204: Count Primes
Given an integer n
, return the number of prime numbers that are strictly less than n
.
To count the number of prime numbers less than ( n ), we can use the Sieve of Eratosthenes technique:
isPrime
of size ( n ) where each entry isPrime[i]
will be true
if i
is a prime number, initially assuming all numbers are prime.p
that is still marked as prime, mark all multiples of p
(starting from ( p \times p )) as non-prime.true
values in the isPrime
array from index 2 to ( n-1 ) will give the count of prime numbers less than ( n ).public class CountPrimes {
public int countPrimes(int n) {
if (n <= 2) return 0;
boolean[] isPrime = new boolean[n];
// Initialize all entries as true, except for index 0 and 1 which are not primes
for (int i = 2; i < n; i++) {
isPrime[i] = true;
}
for (int i = 2; i * i < n; i++) {
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) {
isPrime[j] = false;
}
}
}
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) count++;
}
return count;
}
public static void main(String[] args) {
CountPrimes cp = new CountPrimes();
System.out.println(cp.countPrimes(10)); // Output: 4 (2, 3, 5, 7)
System.out.println(cp.countPrimes(0)); // Output: 0
System.out.println(cp.countPrimes(1)); // Output: 0
}
}
The time complexity of the Sieve of Eratosthenes algorithm is ( O(n \log \log n) ) because each prime number’s multiples are marked in approximately ( O(\log \log n) ) operations. This is a near-linear time complexity, making it efficient for large values of ( n ).
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?