-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountPrime.cpp
51 lines (39 loc) · 958 Bytes
/
countPrime.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
#include <bits/stdc++.h>
using namespace std;
#define N 5e6
// vector<bool> isprime(N, true);
int countp = 0;
class Solution {
public:
void sieve (int n) {
vector<bool> isprime (n+1, true);
isprime[0] = isprime[1] = false;
int i = 0;
countp = 0;
for (i = 2; i*i <= n; i++) { // this stops from overflow.
if (isprime[i] == true) {
countp++;
for (int j = i*i; j <= n; j+=i) {
isprime[j] = false;
}
}
}
for (; i < n; i++) {
if (isprime[i] == true) {
countp++;
}
}
}
int countPrimes(int n) {
sieve(n);
return countp;
}
};
int main() {
int n;
cin >> n;
Solution obj;
int ans = obj.countPrimes(n);
cout << "Ans:: " << ans << endl;
return 0;
}