Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created December 26, 2019 16:46
Show Gist options
  • Save thinkphp/e9f4caff1ee8b5b0c842c1c65f151f47 to your computer and use it in GitHub Desktop.
Save thinkphp/e9f4caff1ee8b5b0c842c1c65f151f47 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
/**
*
* Eratosthenes of Cyrene.
*
*/
#include <iostream>
#include <cstdlib>
using namespace std;
namespace Primes {
bool isPrime(int n) {
int i;
i = 2;
bool ok = true;
while(ok && i*i <= n) {
ok = (n % i != 0);
i++;
}
return ok;
};
namespace Eratosthenes {
void display(int n) {
for(int i = 2; i <= n; ++i) {
if( Primes::isPrime(i) ) cout<<i<<" ";
}
cout<<endl;
}
int getCounts(int n) {
bool list[ n + 1 ];
int totalPrimes = n - 1;
for(int i = 2; i < n + 1; ++i) list[ i ] = true;
int i, j;
for(i = 2; i * i <= n; i++) {
if( list[ i ] ) {
j = 2;
while(i * j <= n) {
int multiply = i * j;
if( list[multiply] ) {
totalPrimes--;
}
list[ multiply ] = false;
j++;
}
}
}
return totalPrimes;
}
void __display(int n) {
bool Primes[n + 1];
for(int i = 2; i <= n; i++) Primes[ i ] = true;
int i, j;
for(i = 2; i * i <= n; ++i) {
if(Primes[ i ]) {
j = 2;
while(i*j <= n) {
int multiply = i * j;
Primes[multiply] = false;
j++;
}
}
}
for(i = 2; i <= n; ++i)
if(Primes[ i ]) cout<<i<<",";
cout<<endl;
}
}
};
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
cout<<Primes::Eratosthenes::getCounts(n)<<endl;
Primes::Eratosthenes::display(n);
Primes::Eratosthenes::__display(n);
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment