
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)
1def is_prime
In Python, the naive solution applies a similar is_prime function, utilizing trial division to assess the primality of each number less than n. Despite being less efficient, it demonstrates a straightforward necessity for optimization with larger inputs.