-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode204_count_primes.cpp
59 lines (49 loc) · 1.2 KB
/
leetcode204_count_primes.cpp
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
/**
* @file leetcode204_count_primes.cpp
* @author wangguibao(https://github.com/wangguibao)
* @date 2023/09/06 10:42
* @brief https://leetcode.com/problems/count-primes/
*
**/
#include <iostream>
#include <vector>
using namespace std;
/**
* Count number of primes using Sieve of Eratosthenes
*/
class Solution {
public:
int countPrimes(int n) {
std::vector<bool> bits(n + 1);
for (int i = 0; i <= n; ++i) {
bits[i] = true;
}
for (int i = 2; i * i <= n; ++i) {
if (bits[i] == true) {
for (int j = i * i; j <= n; j += i) {
bits[j] = false;
}
}
}
int total = 0;
for (int i = 2; i < n; ++i) {
if (bits[i] == true) {
++total;
}
}
return total;
}
};
int main() {
int n;
while (1) {
std::cout << "Input n (Ctrl-C to exit): " << std::endl;
if (!(std::cin >> n)) {
return 0;
}
Solution solution;
auto ret = solution.countPrimes(n);
std::cout << ret << std::endl;
}
return 0;
}