-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path7.29.cpp
More file actions
39 lines (30 loc) · 962 Bytes
/
7.29.cpp
File metadata and controls
39 lines (30 loc) · 962 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
//The sieve of Eratosthenes
#include <iostream>
using namespace std;
#define TOTAL_INTEGERS 1000000
int main(void){
// bool is 1 byte, int is 4 bytes - creating a bool array to save space
bool numbers[TOTAL_INTEGERS] = {};
int multiple; // track the index to the multiple of current index
// initialize everything to true
for (int i=2; i< TOTAL_INTEGERS; i++){
numbers[i] = true;
}
// ignore first two elements
for (int i=2; i< TOTAL_INTEGERS; i++){
multiple = 2;
// set all multiples of current entry to false
while(i * multiple < TOTAL_INTEGERS){
numbers[i*multiple] = false;
multiple++;
}
}
// Print all the prime numbers
cout << "Prime numbers between 2 and " << TOTAL_INTEGERS << " are: " << endl;
for (int i=2; i<TOTAL_INTEGERS; i++){
if (numbers[i] == true){
cout << i << " ";
}
}
return 0;
}