Added tests for Sieve of Eratosthenes

This commit is contained in:
2021-06-30 17:14:56 -04:00
parent 83c20463de
commit 279528fe28
2 changed files with 75 additions and 4 deletions

View File

@@ -108,7 +108,9 @@ 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){}
SieveOfEratosthenes(){
possiblePrime = 2;
}
bool hasNext(){
return true;
}
@@ -124,14 +126,53 @@ public:
//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);
//Move on to the next possible prime
possiblePrime += 2;
}
else{
//Return 2 and move to 3
prime = possiblePrime++;
}
return prime;
}
};
template <class T>
class SieveOfEratosthenesAlt{
private:
T possiblePrime; //The next number that could be a prime
std::map<T, std::vector<T>> compositeMap; //A map to keep track of all of the composite numbers
public:
SieveOfEratosthenesAlt(){
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);
}
//Save that it is a prime
prime = possiblePrime;
//Add the next entry to the prime
compositeMap[prime * 3].push_back(prime);
//Move on to the next possible prime
possiblePrime += 2;
}
else{
//Return 2 and move to 3
prime = possiblePrime++;
}
return prime;