-
Notifications
You must be signed in to change notification settings - Fork 0
/
sieve_of_erasthoneses.cpp
83 lines (55 loc) · 1.69 KB
/
sieve_of_erasthoneses.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
/*
-------------------------------------------------------
Info : Sieve of eurosthenes implementation using
C++ vector container. Given upper limit,
this will list all the prime number upto
that range
Date : 6th June 2017
Author : Sarvesh Jayaraman
contact : [email protected]
-------------------------------------------------------
*/
#include <iostream>
#include <vector>
#include <cmath>
#include <chrono>
//timing operations
#define INIT_TIMER auto start=std::chrono::high_resolution_clock::now();
#define START_TIMER start=std::chrono::high_resolution_clock::now();
#define STOP_TIMER std::cout << "RUNTIME is "<< std::chrono::duration_cast <std::chrono::milliseconds> (\
std::chrono::high_resolution_clock::now()-start).count() <<"ms\n" ;
void sieve_of_erasthoneses(int n){//,
//initialize the sieve as vector of boolean!
//initially assume all numbers are prime
std::vector<bool> sieve(n,true);
// numbers 0 and 1
sieve[0]=false;
sieve[1]=false;
for (int a=2;a<=std::sqrt(n);++a){
//std::cout<<a<<"\n";
// get the multiples of a and mark as not prime
for (int i=2*a;i<=n;i+=a)
sieve[i]=false;
}
std::cout <<"size of sieve is :" << sieve.size() <<"\n";
std::cout <<"=======================\n"
<<"Numbers are as follows:\n"
<<"=======================\n";
// print sieve elements marked by true flag, which indicates
// they are prime numbers!
for (int i=0;i<sieve.size();i++){
if (sieve[i])
std::cout <<i<<"\n";
}
}
//main function
int main(){
int n=1000000;
//initialize and start timer
INIT_TIMER
START_TIMER
// compute prime numbers using sieve of erasthoneses method!
sieve_of_erasthoneses(n);
STOP_TIMER
return 0;
}