2017-10-09 09:34:50 +08:00
|
|
|
/*
|
|
|
|
* Sieve of Eratosthenes is an algorithm to find the primes
|
|
|
|
* that is between 2 to N (as defined in main).
|
|
|
|
*
|
2018-09-13 08:27:56 +08:00
|
|
|
* Time Complexity : O(N * log N)
|
2017-10-09 09:34:50 +08:00
|
|
|
* Space Complexity : O(N)
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
#define MAX 10000000
|
|
|
|
|
2018-09-13 08:27:56 +08:00
|
|
|
int isprime[MAX];
|
2017-10-09 09:34:50 +08:00
|
|
|
|
|
|
|
/*
|
|
|
|
* This is the function that finds the primes and eliminates
|
|
|
|
* the multiples.
|
|
|
|
*/
|
2019-08-21 10:10:08 +08:00
|
|
|
void sieve(int N)
|
|
|
|
{
|
2018-09-13 08:27:56 +08:00
|
|
|
isprime[0] = 0;
|
|
|
|
isprime[1] = 0;
|
2019-08-21 10:10:08 +08:00
|
|
|
for (int i = 2; i <= N; i++)
|
|
|
|
{
|
|
|
|
if (isprime[i])
|
|
|
|
{
|
|
|
|
for (int j = i * 2; j <= N; j += i)
|
|
|
|
{
|
2018-09-13 08:27:56 +08:00
|
|
|
isprime[j] = 0;
|
|
|
|
}
|
|
|
|
}
|
2017-10-09 09:34:50 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* This function prints out the primes to STDOUT
|
|
|
|
*/
|
2019-08-21 10:10:08 +08:00
|
|
|
void print(int N)
|
|
|
|
{
|
|
|
|
for (int i = 1; i <= N; i++)
|
|
|
|
{
|
|
|
|
if (isprime[i] == 1)
|
|
|
|
{
|
2018-09-13 08:27:56 +08:00
|
|
|
cout << i << ' ';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
cout << '\n';
|
2017-10-09 09:34:50 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* NOTE: This function is important for the
|
|
|
|
* initialization of the array.
|
|
|
|
*/
|
2019-08-21 10:10:08 +08:00
|
|
|
void init()
|
|
|
|
{
|
|
|
|
for (int i = 1; i < MAX; i++)
|
|
|
|
{
|
2018-09-13 08:27:56 +08:00
|
|
|
isprime[i] = 1;
|
|
|
|
}
|
2017-10-09 09:34:50 +08:00
|
|
|
}
|
|
|
|
|
2019-08-21 10:10:08 +08:00
|
|
|
int main()
|
|
|
|
{
|
2018-09-13 08:27:56 +08:00
|
|
|
int N = 100;
|
|
|
|
init();
|
|
|
|
sieve(N);
|
|
|
|
print(N);
|
2017-10-09 09:34:50 +08:00
|
|
|
}
|