Created
September 22, 2017 03:05
-
-
Save BenGoldberg1/d3f31212fc6a96c77926b9505a8b8441 to your computer and use it in GitHub Desktop.
Yet another primes streamer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 awhile(1)
and it would run forever.See https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Incremental_sieve