Last active
December 23, 2015 19:08
-
-
Save ahammel/6680067 to your computer and use it in GitHub Desktop.
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 <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(); | |
} | |
} | |
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
#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