
Sponsored
Sponsored
The Sieve of Eratosthenes is a classic algorithm to find all prime numbers up to a given limit. It efficiently marks non-prime numbers in a boolean array, allowing us to count the prime numbers left unmarked.
It operates by marking the multiples of each prime starting from 2, the smallest prime. This optimization significantly reduces the number of operations needed compared to checking each number individually.
Time Complexity: O(n log log n)
Space Complexity: O(n)
1import java.util.Arrays;
2
3public class Solution {
4 public int countPrimes(int n) {
5 if (n <= 2) return 0;
6 boolean[] isPrime = new boolean[n];
7 Arrays.fill(isPrime, true);
8 isPrime[0] = isPrime[1] = false;
9 for (int i = 2; i * i < n; i++) {
10 if (isPrime[i]) {
11 for (int j = i * i; j < n; j += i) {
12 isPrime[j] = false;
13 }
14 }
15 }
16 int count = 0;
17 for (boolean prime : isPrime) {
18 if (prime) count++;
19 }
20 return count;
21 }
22
23 public static void main(String[] args) {
24 Solution sol = new Solution();
25 System.out.println(sol.countPrimes(10)); // Output: 4
26 }
27}
28The Java solution uses an array of booleans to track prime status for each integer. A single pass through numbers whose squares are below n suffices to mark multiples as non-prime, achieving the desired sieve effect.
A more basic approach to this problem is to check each number individually for primality. This involves testing each number for factors up to its square root. While less efficient than the sieve, it provides an instructive example of brute force in algorithm design.
Time Complexity: O(n√n)
Space Complexity: O(1)
1#include <iostream>
2#include <cmath>
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
int countPrimes(int n) {
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime(i)) count++;
}
return count;
}
int main() {
std::cout << countPrimes(10) << std::endl; // Output: 4
return 0;
}
The C++ variant follows a similar logic to the C solution, evaluating primality for each number below n using a naive method. The isPrime function tests potential factors selectively for efficiency.