mirror of
https://bitbucket.org/Mattrixwv/my-classes.git
synced 2025-12-06 18:23:57 -05:00
Added a SieveOfEratosthenes class
This commit is contained in:
@@ -28,6 +28,8 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <map>
|
||||||
|
|
||||||
namespace mee{
|
namespace mee{
|
||||||
|
|
||||||
@@ -93,6 +95,41 @@ T findMax(const std::vector<T>& ary);
|
|||||||
int findNumOccurrence(std::string str, char ch);
|
int findNumOccurrence(std::string str, char ch);
|
||||||
|
|
||||||
|
|
||||||
|
template <class T>
|
||||||
|
class SieveOfEratosthenes{
|
||||||
|
private:
|
||||||
|
T possiblePrime; //The next number that could be a prime
|
||||||
|
std::unordered_map<T, std::vector<T>> 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
|
//This is a function that returns all the primes <= goalNumber and returns a vector with those prime numbers
|
||||||
template <class T>
|
template <class T>
|
||||||
std::vector<T> getPrimes(T goalNumber){
|
std::vector<T> getPrimes(T goalNumber){
|
||||||
|
|||||||
Reference in New Issue
Block a user