mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-25 02:53:18 +08:00
documentation and bug fixes
This commit is contained in:
@@ -1,69 +1,65 @@
|
||||
/*
|
||||
* Sieve of Eratosthenes is an algorithm to find the primes
|
||||
/**
|
||||
* @file
|
||||
* @brief Get list of prime numbers using Sieve of Eratosthenes
|
||||
* Sieve of Eratosthenes is an algorithm to find the primes
|
||||
* that is between 2 to N (as defined in main).
|
||||
*
|
||||
* Time Complexity : O(N * log N)
|
||||
* Space Complexity : O(N)
|
||||
* 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
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
/** Maximum number of primes */
|
||||
#define MAX 10000000
|
||||
|
||||
int isprime[MAX];
|
||||
/** array to store the primes */
|
||||
bool isprime[MAX];
|
||||
|
||||
/*
|
||||
* This is the function that finds the primes and eliminates
|
||||
/**
|
||||
* This is the function that finds the primes and eliminates
|
||||
* the multiples.
|
||||
*/
|
||||
void sieve(int N)
|
||||
{
|
||||
isprime[0] = 0;
|
||||
isprime[1] = 0;
|
||||
for (int i = 2; i <= N; i++)
|
||||
{
|
||||
if (isprime[i])
|
||||
{
|
||||
for (int j = i * 2; j <= N; j += i)
|
||||
{
|
||||
isprime[j] = 0;
|
||||
void sieve(uint32_t N) {
|
||||
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) {
|
||||
isprime[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
/**
|
||||
* This function prints out the primes to STDOUT
|
||||
*/
|
||||
void print(int N)
|
||||
{
|
||||
for (int i = 1; i <= N; i++)
|
||||
{
|
||||
if (isprime[i] == 1)
|
||||
{
|
||||
cout << i << ' ';
|
||||
void print(uint32_t N) {
|
||||
for (uint32_t i = 1; i <= N; i++) {
|
||||
if (isprime[i]) {
|
||||
std::cout << i << ' ';
|
||||
}
|
||||
}
|
||||
cout << '\n';
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
/*
|
||||
* NOTE: This function is important for the
|
||||
* initialization of the array.
|
||||
/**
|
||||
* Initialize the array
|
||||
*/
|
||||
void init()
|
||||
{
|
||||
for (int i = 1; i < MAX; i++)
|
||||
{
|
||||
isprime[i] = 1;
|
||||
void init() {
|
||||
for (uint32_t i = 1; i < MAX; i++) {
|
||||
isprime[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int N = 100;
|
||||
/** main function */
|
||||
int main() {
|
||||
uint32_t N = 100;
|
||||
init();
|
||||
sieve(N);
|
||||
print(N);
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user