2017-12-24 01:30:49 +08:00
|
|
|
/*
|
|
|
|
* 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;
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int i = 2; i <= N; i++)
|
|
|
|
{
|
|
|
|
if (primes[i] == 1)
|
|
|
|
continue;
|
|
|
|
for (int j = i + i; j <= N; j += i)
|
|
|
|
primes[j] = 1;
|
|
|
|
}
|
2017-12-24 01:30:49 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* This function prints out the primes to STDOUT
|
|
|
|
*/
|
|
|
|
void print(int N)
|
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int i = 0; i <= N; i++)
|
|
|
|
if (primes[i] == 0)
|
2017-12-24 01:30:49 +08:00
|
|
|
cout << i << ' ';
|
|
|
|
cout << '\n';
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* NOTE: This function is important for the
|
|
|
|
* initialization of the array.
|
|
|
|
*/
|
|
|
|
void init()
|
|
|
|
{
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int i = 0; i < MAX; i++)
|
2017-12-24 01:30:49 +08:00
|
|
|
primes[i] = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
int main()
|
|
|
|
{
|
|
|
|
int N = 100;
|
|
|
|
init();
|
|
|
|
sieve(N);
|
|
|
|
print(N);
|
|
|
|
}
|