-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountprimes.cpp
More file actions
44 lines (43 loc) · 949 Bytes
/
countprimes.cpp
File metadata and controls
44 lines (43 loc) · 949 Bytes
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
class Solution {
public:
int countPrimes(int n) {
if (n <= 2)
{
return 0;
}
vector<bool>prime(n, false);
int count = n-2;
prime[0] = false;
prime[1] = false;
prime[2] = true;
for (int i = 3; i < n; i++)
{
prime[i] = i % 2 != 0;
}
if (n & 0x1)
{
count = count - count / 2 ;
}
else
{
count = count - count / 2 + 1;
}
int sq = sqrt(n);
for (int i = 3; i <= sq; i+=2)
{
if (prime[i])
{
for (int j = i*i; j < n; j += 2*i)
{
if (prime[j] == false)
{
continue;
}
prime[j] = false;
count--;
}
}
}
return count;
}
};