-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_0204_countPrimes.cc
More file actions
60 lines (55 loc) · 1.22 KB
/
Copy pathProblem_0204_countPrimes.cc
File metadata and controls
60 lines (55 loc) · 1.22 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
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
// 埃式筛法
int countPrimes(int n)
{
if (n < 3)
{
return 0;
}
// f[i] true表示被筛选过
vector<bool> f(n);
// 首先排除一半的数,因为偶数一定不是质数
int count = n / 2;
// 筛选所有的奇数,注意这里的上界是 i*i < n
for (int i = 3; i * i < n; i += 2)
{
if (f[i])
{
continue;
}
// 筛选所有能被i整除的奇数
// 为什么 j 从 i*i 开始 ?
// 首先,(i-1)*i 是偶数(因为i-1是偶数),前面已经排除
// 其次,(i-2)*i 在枚举上一个数i-2时, (i-2)*(i-2)、(i-2)*i、(i-2)*(3i - 2) ... 已经枚举过了
// 同理,(i-3)*i,(i-4)*i,... 都在前面枚举过
for (int j = i * i; j < n; j += 2 * i)
{
if (!f[j])
{
count--;
f[j] = true;
}
}
}
return count;
}
};
void testCountPrimes()
{
Solution s;
EXPECT_EQ_INT(0, s.countPrimes(1));
EXPECT_EQ_INT(4, s.countPrimes(10));
EXPECT_EQ_INT(0, s.countPrimes(0));
EXPECT_SUMMARY;
}
int main()
{
testCountPrimes();
return 0;
}