Skip to content

Commit 006caaf

Browse files
committed
递推:质数统计
Change-Id: Ib56fc058036f12891592bf200c28632c41a3dd19
1 parent abc16fc commit 006caaf

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

go/leetcode/204.计数质数.go

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* @lc app=leetcode.cn id=204 lang=golang
3+
*
4+
* [204] 计数质数
5+
*
6+
* https://leetcode-cn.com/problems/count-primes/description/
7+
*
8+
* algorithms
9+
* Easy (38.19%)
10+
* Likes: 702
11+
* Dislikes: 0
12+
* Total Accepted: 150.5K
13+
* Total Submissions: 394.1K
14+
* Testcase Example: '10'
15+
*
16+
* 统计所有小于非负整数 n 的质数的数量。
17+
*
18+
*
19+
*
20+
* 示例 1:
21+
*
22+
* 输入:n = 10
23+
* 输出:4
24+
* 解释:小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
25+
*
26+
*
27+
* 示例 2:
28+
*
29+
* 输入:n = 0
30+
* 输出:0
31+
*
32+
*
33+
* 示例 3:
34+
*
35+
* 输入:n = 1
36+
* 输出:0
37+
*
38+
*
39+
*
40+
*
41+
* 提示:
42+
*
43+
*
44+
* 0 <= n <= 5 * 10^6
45+
*
46+
*
47+
*/
48+
49+
// @lc code=start
50+
func countPrimes(n int) int {
51+
// 1. 对于每一个数,从2开始到根号n试探是否能被整除,到根号n是因为大于根号n之后,另外一个因子也必然小于根号n
52+
// 2. 假如一个数是质数,那2x,3x就不再是质数,可以递推一直标记到n
53+
// 3. 2中的标记会有重复,比如24,2、3、4、6、8、12都会算一次,可以用线性筛优化,具体不展开
54+
composite := make([]bool, n)
55+
count := 0
56+
for i := 2; i < n; i++ {
57+
if !composite[i] {
58+
count++
59+
for j := i + i; j < n; j += i {
60+
composite[j] = true
61+
}
62+
}
63+
}
64+
return count
65+
}
66+
67+
// @lc code=end
68+

0 commit comments

Comments
 (0)