LeetCode 204: Count Primes Solution
Master LeetCode problem 204 (Count Primes), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
204. Count Primes
Problem Explanation
Explanation
To solve this problem, we can use the Sieve of Eratosthenes algorithm. The algorithm works by iteratively marking the multiples of each prime starting from 2 as composite numbers. After this process, the unmarked numbers left are prime numbers. We can count the number of prime numbers less than n
using this algorithm.
Algorithm:
- Initialize a boolean array
isPrime
of sizen
and set all values totrue
. - Start from 2 (first prime number) and iterate up to the square root of
n
. - For each prime number
p
, ifisPrime[p]
is true, mark all multiples ofp
as non-prime by settingisPrime[p*i] = false
wherei
ranges from 2 ton/p
. - Finally, count the number of
true
values in theisPrime
array, excluding 0 and 1.
Time Complexity: O(n log log n)
Space Complexity: O(n)
Solution Code
class Solution {
public int countPrimes(int n) {
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, 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;
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 204 (Count Primes)?
This page provides optimized solutions for LeetCode problem 204 (Count Primes) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 204 (Count Primes)?
The time complexity for LeetCode 204 (Count Primes) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 204 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 204 in Java, C++, or Python.