-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathe14.cpp
62 lines (53 loc) · 997 Bytes
/
e14.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
#include "../std_lib_facilities.h"
struct Primes
{
int number;
bool prime;
};
int main ()
{
int max {0};
cout << "Enter e number to find all primes below with the Sieve of Eratosthenes method:" << endl;
cin >> max;
// initializing
vector<Primes> primes;
for (int i {2} ; i <= max ; ++i)
{
primes.push_back({i, true});
}
// calculating
for (int i = 0 ; i * i < max ; ++i)
{
for (int j = primes[i].number ; j + i < primes.size() ; j += primes[i].number)
{
primes[j + i].prime = false;
}
}
// printing
int total_primes {0};
for (auto prime: primes)
{
if (prime.prime)
{
++total_primes;
}
}
cout << "There are " << total_primes << " primes, under " << max << "."<< endl;
cout << "The primes are: ";
for (int i = 0, cnt = 0; i != primes.size(); ++i)
{
if (primes[i].prime)
{
++cnt;
cout << primes[i].number;
if (cnt < total_primes)
{
cout << ", ";
}
else if (cnt == total_primes)
{
cout << ".";
}
}
}
}