-
Notifications
You must be signed in to change notification settings - Fork 0
/
count_primes.cpp
84 lines (73 loc) · 1.53 KB
/
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// 204. Count Primes: https://leetcode.com/problems/count-primes
// Author: [email protected]
#include <stdio.h>
#include <stdlib.h>
#include <vector>
// Brute force
class Solution1
{
public:
int countPrimes(int n)
{
std::vector<int> primes(1, 2);
for (int i = 3; i < n; i++)
{
bool is_prime = true;
for (auto j: primes)
{
if ((j * j) <= i && (i % j) == 0)
{
is_prime = false;
break;
}
}
if (is_prime)
{
primes.push_back(i);
}
}
return (n > 2 ? primes.size() : 0);
}
};
// Sieve of Eratosthenes
class Solution2
{
public:
int countPrimes(int n)
{
std::vector<bool> primes(n, true);
for (int i = 2; i * i < n; i++)
{
if (!primes[i])
{
continue;
}
for (int j = i * i; j < n; j += i)
{
primes[j] = false;
}
}
int count = 0;
for (int i = 2; i < n; i++)
{
if (primes[i])
{
count++;
}
}
return count;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
int n = 10;
if (argc > 1)
{
n = atoi(argv[1]);
}
int count = Solution().countPrimes(n);
printf("Input: %d\n", n);
printf("Output: %d\n", count);
return 0;
}