-
Notifications
You must be signed in to change notification settings - Fork 1
/
cppPrimeSieve.cpp
138 lines (111 loc) · 2.47 KB
/
cppPrimeSieve.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
* @file primeSieve.cpp
* @author your name ([email protected])
* @brief
*/
// --- includes --- //
#include <iostream>
#include <vector>
#include <math.h>
// --- namespace --- //
using namespace std;
// --- function declarations --- //
vector<bool> primeSieve(vector<bool> primes);
bool primeCheck(vector<bool> primes);
bool isPrime(int number);
// main!
int main(int argc, char const *argv[])
{
// inits
vector<bool> primes;
int passCount;
int size;
// Get command line input
if (argc > 1) {
size = stoi(argv[1]);
passCount = stoi(argv[2]);
}
else {
return -1;
}
// fill the vector with all true primes as placeholders
for (int i = 0; i < size; ++i) {
primes.push_back(true);
}
// run the sieve
for (int i = 0; i < passCount; ++i) {
// reset primes array to all true
for (int j = 0; j < primes.size() - 1; ++j) {
primes[j] = true;
}
// run sieve
primes = primeSieve(primes);
}
// verify primes
if (!primeCheck(primes)) {
return -1;
}
// return successfully! :)
return 0;
}
/**
* @brief prime sieve
*
* @param count the max value to search to
* @param primes
*/
vector<bool> primeSieve(vector<bool> primes) {
primes[0] = false;
primes[1] = false;
// loop through the prime array marking non-primes as false
int smallerLimit = (int) sqrt(primes.size()) + 1;
for (int i = 3; i < smallerLimit; ++i) {
if (primes[i]) {
for (int j = (i * i); j < primes.size() - 1; j+=i) {
primes[j] = false;
}
}
}
return primes;
}
/**
* @brief
*
* @param primes
* @return true
* @return false
*/
bool primeCheck(vector<bool> primes) {
bool valid = true;
for (int i = 0; i < (primes.size() - 1); ++i) {
if (primes.at(i)) {
if (!isPrime(i)) {
valid = false;
}
}
}
return valid;
}
/**
* @brief
*
* @return true
* @return false
*/
bool isPrime(int number) {
// catch early primes and eliminate all numbers divisable by 2
if (number == 2) {
return true;
}
if (number < 2 || number % 2 == 0) {
return false;
}
// if the number is larger
for (int i = 3; (i * i) <= number; i += 2) {
if (number % i == 0) {
return false;
}
}
// otherwise the number is prime!
return true;
}