TheAlgorithms-C-Plus-Plus/math/sieve_of_eratosthenes.cpp

76 lines
1.3 KiB
C++
Raw Normal View History

2020-05-28 04:45:33 +08:00
/**
* @file
* @brief Get list of prime numbers using Sieve of Eratosthenes
* Sieve of Eratosthenes is an algorithm to find the primes
2017-10-09 09:34:50 +08:00
* that is between 2 to N (as defined in main).
*
2020-05-28 04:45:33 +08:00
* Time Complexity : \f$O(N \cdot\log N)\f$
* <br/>Space Complexity : \f$O(N)\f$
*
* @see primes_up_to_billion.cpp prime_numbers.cpp
2017-10-09 09:34:50 +08:00
*/
#include <iostream>
2020-05-28 04:45:33 +08:00
/** Maximum number of primes */
2017-10-09 09:34:50 +08:00
#define MAX 10000000
2020-05-28 04:45:33 +08:00
/** array to store the primes */
bool isprime[MAX];
2017-10-09 09:34:50 +08:00
2020-05-28 04:45:33 +08:00
/**
* This is the function that finds the primes and eliminates
2017-10-09 09:34:50 +08:00
* the multiples.
*/
void sieve(uint32_t N)
{
2020-05-28 04:45:33 +08:00
isprime[0] = false;
isprime[1] = false;
for (uint32_t i = 2; i <= N; i++)
{
if (isprime[i])
{
for (uint32_t j = (i << 1); j <= N; j += i)
{
2020-05-28 04:45:33 +08:00
isprime[j] = false;
}
}
2017-10-09 09:34:50 +08:00
}
}
2020-05-28 04:45:33 +08:00
/**
2017-10-09 09:34:50 +08:00
* This function prints out the primes to STDOUT
*/
void print(uint32_t N)
{
for (uint32_t i = 1; i <= N; i++)
{
if (isprime[i])
{
2020-05-28 04:45:33 +08:00
std::cout << i << ' ';
}
}
2020-05-28 04:45:33 +08:00
std::cout << std::endl;
2017-10-09 09:34:50 +08:00
}
2020-05-28 04:45:33 +08:00
/**
* Initialize the array
2017-10-09 09:34:50 +08:00
*/
void init()
{
for (uint32_t i = 1; i < MAX; i++)
{
2020-05-28 04:45:33 +08:00
isprime[i] = true;
}
2017-10-09 09:34:50 +08:00
}
2020-05-28 04:45:33 +08:00
/** main function */
int main()
{
2020-05-28 04:45:33 +08:00
uint32_t N = 100;
init();
sieve(N);
print(N);
2020-05-28 04:45:33 +08:00
return 0;
2017-10-09 09:34:50 +08:00
}