Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created December 25, 2019 22:14
Show Gist options
  • Save thinkphp/16b850a8004f37f142c6e85b9f2c3351 to your computer and use it in GitHub Desktop.
Save thinkphp/16b850a8004f37f142c6e85b9f2c3351 to your computer and use it in GitHub Desktop.
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<<" ";
}
}
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;
}
}
};
int main(int argc, char *argv[]) {
int n;
cin>>n;
cout<<Primes::Eratosthenes::getCounts(n)<<endl;
Primes::Eratosthenes::display(n);
cout<<endl;
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment