Skip to content

Instantly share code, notes, and snippets.

@ahammel
Last active December 23, 2015 19:08
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 ahammel/6680067 to your computer and use it in GitHub Desktop.
Save ahammel/6680067 to your computer and use it in GitHub Desktop.
#include <prime_generator.h>
#include <iostream>
unsigned long PrimeGenerator::next()
{
unsigned long factor;
unsigned long next_composite;
if (next_candidate >= max_value) {
throw "Integer overfow!\n";
}
if ( !lazy_sieve.count(next_candidate) ) {
lazy_sieve[next_candidate * next_candidate] = next_candidate;
return next_candidate++;
} else {
factor = lazy_sieve.at(next_candidate);
next_composite = next_candidate + factor;
while ( lazy_sieve.count(next_composite) ) {
next_composite += factor;
}
lazy_sieve[next_composite] = factor;
lazy_sieve.erase(next_candidate);
++next_candidate;
next();
}
}
#ifndef PRIME_GENERATOR_H
#define PRIME_GENERATOR_H
#include <limits.h>
#include <unordered_map>
using namespace std;
class PrimeGenerator
{
public:
PrimeGenerator(unsigned long max = ULONG_MAX) : max_value(max)
{
next_candidate = 2;
}
unsigned long next();
private:
unsigned long next_candidate;
std::unordered_map<unsigned long, unsigned long> lazy_sieve;
const unsigned long max_value;
};
#endif /* end of include guard: PRIME_GENERATOR_H */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment