forked from TheAlgorithms/C-Plus-Plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsieve_of_Eratosthenes.cpp
60 lines (52 loc) · 894 Bytes
/
sieve_of_Eratosthenes.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
/*
* Sieve of Eratosthenes is an algorithm to find the primes
* that is between 2 to N (as defined in main).
*
* Time Complexity : O(N)
* Space Complexity : O(N)
*/
#include <iostream>
using namespace std;
#define MAX 10000000
int primes[MAX];
/*
* This is the function that finds the primes and eliminates
* the multiples.
*/
void sieve(int N)
{
primes[0] = 1;
primes[1] = 1;
for(int i=2;i<=N;i++)
{
if(primes[i] == 1) continue;
for(int j=i+i;j<=N;j+=i)
primes[j] = 1;
}
}
/*
* This function prints out the primes to STDOUT
*/
void print(int N)
{
for(int i=0;i<=N;i++)
if(primes[i] == 0)
cout << i << ' ';
cout << '\n';
}
/*
* NOTE: This function is important for the
* initialization of the array.
*/
void init()
{
for(int i=0;i<MAX;i++)
primes[i] = 0;
}
int main()
{
int N = 100;
init();
sieve(N);
print(N);
}