Skip to content

Instantly share code, notes, and snippets.

@BenGoldberg1
Created September 22, 2017 03:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenGoldberg1/d3f31212fc6a96c77926b9505a8b8441 to your computer and use it in GitHub Desktop.
Save BenGoldberg1/d3f31212fc6a96c77926b9505a8b8441 to your computer and use it in GitHub Desktop.
Yet another primes streamer.
#include <iostream>
#include <deque>
// This code requires -std=c++11 or better because lambda.
int main() {
std::deque<unsigned> primes;
std::deque< std::deque<unsigned> > factors( 3 );
unsigned a_prime = 3, a_square_prime = 9, maybe_prime = 3;
std::cout << "2 3";
auto my_insert = [&]( unsigned factor ) {
if( factor >= factors.size() ) factors.resize( factor+1 );
factors[factor].emplace_back( factor );
};
while( maybe_prime <= 9999 ) {
const auto &f = factors.front();
maybe_prime += 2;
if( !f.empty() ) {
for( auto ff = f.rbegin(); ff != f.rend(); ++ff )
my_insert( *ff );
} else if( maybe_prime < a_square_prime ) {
std::cout << " " << maybe_prime;
primes.emplace_back( maybe_prime );
} else {
my_insert( a_prime );
std::swap( a_prime, primes.front() );
primes.pop_front();
a_square_prime = a_prime * a_prime;
}
factors.pop_front();
}
std::cout << std::endl;
return 0;
}
@BenGoldberg1
Copy link
Author

Run it here: http://cpp.sh/93jux
This prime number generator is in the Sieve of Eratosthenes family.
Unlike common SoE implementations, there is no predefined upper limit -- you could replace the while test with a while(1) and it would run forever.
See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Incremental_sieve

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment