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
// @Title: 计数质数 (Count Primes)
// @Author: 15816537946@163.com
// @Date: 2019-09-03 19:19:40
// @Runtime: 12 ms
// @Memory: 4.9 MB
/*
 * @lc app=leetcode.cn id=204 lang=golang
 *
 * [204] 计数质数
 *
 * https://leetcode-cn.com/problems/count-primes/description/
 *
 * algorithms
 * Easy (29.75%)
 * Likes:    194
 * Dislikes: 0
 * Total Accepted:    25.9K
 * Total Submissions: 86.9K
 * Testcase Example:  '10'
 *
 * 统计所有小于非负整数 n 的质数的数量。
 * 
 * 示例:
 * 
 * 输入: 10
 * 输出: 4
 * 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
 * 
 * 
 */
 
 // 厄拉多筛选法
func countPrimes(n int) int {
	a := make([]bool, n)
	cnt := 0
	for i := 2; i<n; i++ {
		if a[i] {
			continue
		}
		for j := i*2;j<n;j+=i {
			a[j] = true
		}
		cnt++
	}
	return cnt
}