-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_204.java
33 lines (31 loc) · 1.06 KB
/
_204.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.fishercoder.solutions.firstthousand;
import java.util.Arrays;
public class _204 {
public static class Solution1 {
/*
* Reference: https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
* This is an ancient algorithm to efficiently count the number of primes up to a given point:
* it does so iteratively by marking composite (i.e. not prime) the multiples of each prime,
* starting from 2, then all remaining ones are prime.
*/
public int countPrimes(int n) {
if (n <= 1) {
return 0;
}
boolean[] isPrime = new boolean[n];
Arrays.fill(isPrime, true);
isPrime[0] = false;
isPrime[1] = false;
int count = 0;
for (int i = 2; i < n; i++) {
if (isPrime[i]) {
count++;
for (int j = 2; i * j < n; j++) {
isPrime[i * j] = false;
}
}
}
return count;
}
}
}