-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
68 lines (62 loc) · 1.43 KB
/
Copy pathmain.cpp
File metadata and controls
68 lines (62 loc) · 1.43 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
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
class Solution {
public:
// 筛选法
int countPrimes(int n) {
vector<int> res(n+1,0);
for(int i = 2; i <= sqrt(n) + 1; i++){
for(int j = 2; j <= n/i; j++){
res[i*j] = 1;
}
}
int count = 0;
for(int i = 2; i < n; i++){
if(res[i] == 0){
count++;
}
}
return count;
}
// 奇数筛选法
int countPrimes1(int n) {
if (n <= 2) return 0;
vector<bool> res(n, false);
int count = 1;
int upper = sqrt(n);
for(int i = 3; i < n; i += 2){ //奇数筛选
if(!res[i]){
count++;
if(i > upper)
continue;
for(int j = i*i; j < n; j += i){
res[j] = true;
}
}
}
return count;
}
int countPrimes2(int n) {
vector<bool> res(n, false);
res[0] = res[1] = true;
for(int i = 2; i < sqrt(n); i++){
if(!res[i]){
for(int j = i*i; j < n; j += i){
res[j] = true;
}
}
}
return count(res.begin(),res.end(),false);
}
};
int main()
{
Solution s;
cout << s.countPrimes2(10) <<endl;
return 0;
}