forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountPrimes.java
More file actions
42 lines (38 loc) · 906 Bytes
/
CountPrimes.java
File metadata and controls
42 lines (38 loc) · 906 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
37
38
39
40
41
42
package normal;
import java.util.Arrays;
import java.util.HashSet;
/**
* @program JavaBooks
* @description: 204.计算质数
* @author: mf
* @create: 2019/11/06 10:44
*/
/*
题目:https://leetcode-cn.com/problems/count-primes/
类型:筛选
难度:easy
*/
/*
输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。s
*/
public class CountPrimes {
public static void main(String[] args) {
System.out.println(countPrimes(10));
}
private static int countPrimes(int n) {
if (n == 0 || n == 1) return 0;
boolean[] num = new boolean[n + 1];
int count = 0;
for (int i = 2; i < n; i++) {
if (num[i] == false) {
count++;
for (int j = 2 * i; j < n + 1; j += i) {
num[j] = true;
}
}
}
return count;
}
}