-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCount Primes.java
More file actions
36 lines (29 loc) · 878 Bytes
/
Count Primes.java
File metadata and controls
36 lines (29 loc) · 878 Bytes
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
34
35
36
/*
Count the number of prime numbers less than a non-negative number, n.
Link: https://leetcode.com/problems/count-primes/
Example: None
Solution: None
Source: https://leetcode.com/discuss/81779/12-ms-java-solution-modified-from-the-hint-method-beats-99-95%25
*/
public class Solution {
public int countPrimes(int n) {
if (n < 3) {
return 0;
}
boolean[] f = new boolean[n];
//Arrays.fill(f, true); boolean[] are initialed as false by default
int count = n / 2;
for (int i = 3; i * i < n; i += 2) {
if (f[i]) {
continue;
}
for (int j = i * i; j < n; j += 2 * i) {
if (!f[j]) {
--count;
f[j] = true;
}
}
}
return count;
}
}