mirror of
https://bitbucket.org/Mattrixwv/my-classes.git
synced 2025-12-06 18:23:57 -05:00
Added tests for Sieve of Eratosthenes
This commit is contained in:
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user