Leetcode 204. Count Primes Sure, let’s break down the problem and proceed step by step.
Given an integer n
, return the number of prime numbers that are strictly less than n
.
Before implementing the solution, here are a few questions to clarify the requirements:
n
we need to consider?n
itself as part of the range to check for primes?Usually, these questions help to clearly understand the limitations and expectations. However, based on the typical problem constraints for LeetCode:
n
is often less than 5 * 10^6
.n
, so n
itself should not be considered.n
.To solve this problem efficiently, we can use the Sieve of Eratosthenes algorithm, which is an efficient way to generate all prime numbers less than a given number n
. The steps are as follows:
isPrime
of size n
, initialized to true
. The index represents the number, and the value at that index indicates if the number is prime.false
(i.e., not prime).true
.n
.true
values in the isPrime
array, which gives the count of prime numbers less than n
.Here’s the implementation in C++:
#include <vector>
#include <iostream>
class Solution {
public:
int countPrimes(int n) {
if (n <= 2) return 0; // No prime number less than 2
std::vector<bool> isPrime(n, true);
isPrime[0] = isPrime[1] = false; // 0 and 1 are not prime numbers
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;
}
};
// Example usage
int main() {
Solution solution;
int n = 10; // Example input
std::cout << "Number of primes less than " << n << ": " << solution.countPrimes(n) << std::endl;
return 0;
}
The time complexity of the Sieve of Eratosthenes algorithm is (O(n \log \log n)). This is because each prime number’s multiples are marked in (n / p) steps, where (p) is a prime number. The sum of the series for (p) over all primes is approximately (O(\log \log n)).
The space complexity is (O(n)) due to the boolean array isPrime
of size n
.
This solution is both time-efficient and space-efficient for the problem constraints typically associated with LeetCode problems.
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?