-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountPrimes.java
More file actions
78 lines (69 loc) · 1.84 KB
/
CountPrimes.java
File metadata and controls
78 lines (69 loc) · 1.84 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package leetcode;
/**
* CountPrimes
* https://leetcode-cn.com/problems/count-primes/
* 204. 计数质数
*
* @since 2020-12-03
*/
public class CountPrimes {
public static void main(String[] args) {
CountPrimes sol = new CountPrimes();
System.out.println(sol.countPrimes(0));
System.out.println(sol.countPrimes(10));
System.out.println(sol.countPrimes(20));
System.out.println(sol.countPrimes(200));
System.out.println(sol.countPrimes(2000));
System.out.println(sol.countPrimes(20000));
System.out.println(sol.countPrimes(200000));
}
public int countPrimes(int n) {
if (n < 2) {
// keng...
return 0;
}
boolean[] isNotPrime = new boolean[n + 1];
isNotPrime[0] = true;
isNotPrime[1] = true;
for (int num = 2; num <= n; num++) {
if (isNotPrime[num]) {
continue;
}
if (isPrime(num)) {
int multi = 2;
while (num * multi <= n) {
isNotPrime[num * multi] = true;
multi++;
}
} else {
isNotPrime[num] = true;
}
}
int size = 0;
// keng, < n, not include =
for (int i = 0; i < n; i++) {
if (!isNotPrime[i]) {
size++;
}
}
return size;
}
private boolean isPrime(int num) {
if (num < 2) {
return false;
}
if (num < 4) {
return true;
}
if (num % 2 == 0) {
return false;
}
int mid = (int) Math.sqrt(num) + 1;
for (int t = 3; t <= mid; t += 2) {
if (num % t == 0) {
return false;
}
}
return true;
}
}