-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
countPrimes.cpp
41 lines (35 loc) · 701 Bytes
/
countPrimes.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
/**
* Count the number of prime numbers less than a non-negative number, n.
*/
#include <iostream>
#include <vector>
#include <cmath>
int countPrimes(int n) {
if ( n <= 2) {
return 0;
}
int x = std::sqrt(n);
std::vector<bool> soe(n, false);
soe[1] = true;
for ( int i = 2; i <= x ; ++i ) {
if (soe[i] == false ) {
for (int j = i * i; j < n; j+=i) {
soe[j] = true;
}
}
}
int count = 0;
for ( int i = 2; i < n; ++i ) {
if(soe[i] == false) {
++count;
}
}
return count;
}
int main() {
std::cout << "Enter a non negative integer:" ;
int n;
std::cin >> n;
std::cout << "Number of primes less than " << n << " are " << countPrimes(n) << std::endl;
return 0;
}