-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetPrimes.cpp
70 lines (43 loc) · 1.25 KB
/
getPrimes.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
#include <stdio.h>
#include <iostream>
using namespace std;
void getPrimes(int limit) {
if (limit <= 1) {
cout << "No primes" << endl;
}
else {
// 2 is the only even prime, and since we know the limit
// is at least 2, we can go ahead and print it out, and
// then we are just dealing with odd numbers.
cout << 2 << " ";
// Starting with 3, count up and test each odd number (i) for
// being a prime until the program reaches a number greater
// than the limit
for (int i = 3; i <= limit; i += 2) {
// Assume the number is a prime, then attempt to disprove it
bool pFlag = true;
// Since we are counting odd numbers only, nothing will be
// divisible by 2, so starting checking for divisibility with
// 3 and test every single number (j) until (i) is reached
for (int j = 3; j < i; j++) {
// If (i) is divisible by any number (j) with no remainder,
// then (i) is not a prime
if (i%j == 0) {
pFlag = false;
}
}
// If the loop doesn't disprove (i) as a prime, then it must
// be a prime and should be printed to the screen.
if (pFlag) {
cout << i << " ";
}
}
}
}
int main() {
int x;
cout << "Count primes up to what number? ";
cin >> x;
getPrimes(x);
return 0;
}