diff --git a/Algorithms.hpp b/Algorithms.hpp index 7296aff..ca2ccdc 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -28,6 +28,8 @@ #include #include #include +#include +#include namespace mee{ @@ -93,6 +95,41 @@ T findMax(const std::vector& ary); int findNumOccurrence(std::string str, char ch); +template +class SieveOfEratosthenes{ +private: + T possiblePrime; //The next number that could be a prime + std::unordered_map> compositeMap; //A map to keep track of all of the composite numbers +public: + SieveOfEratosthenes(): possiblePrime(2){} + bool hasNext(){ + return true; + } + T next(){ + T prime; + if(possiblePrime > 2){ + //Loop until you find a prime number + for(;compositeMap[possiblePrime].size() > 0;possiblePrime += 2){ + //Create the next entry for all entries in the map + for(T num : compositeMap[possiblePrime]){ + compositeMap[possiblePrime + num + num].push_back(num); + } + //Delete the current entry + compositeMap.erase(possiblePrime); + } + //If the number is a prime + //Save that it is a prime + prime = possiblePrime; + //Add the next entry to the prime + compositeMap[prime * 3].push_back(prime); + possiblePrime += 2; + } + else{ + prime = possiblePrime++; + } + return prime; + } +}; //This is a function that returns all the primes <= goalNumber and returns a vector with those prime numbers template std::vector getPrimes(T goalNumber){