Updated the getDivisors funct to fix possible bugs and improve efficency

This commit is contained in:
2019-01-31 12:21:55 -05:00
parent 4dfb5f42a4
commit 77586965ca

View File

@@ -196,20 +196,34 @@ std::vector<T> getFactors(T goalNumber){
template<class T> template<class T>
std::vector<T> getDivisors(T num){ std::vector<T> getDivisors(T num){
std::vector<T> divisors; //Holds the number of divisors std::vector<T> divisors; //Holds the number of divisors
//You only need to go to sqrt(number). cnt * cnt is faster than sqrt() //Ensure the parameter is a valid number
for(uint64_t cnt = 1;cnt * cnt <= num;++cnt){ if(num <= 0){
return divisors;
}
else if(num == 1){
divisors.push_back(1);
}
else{
divisors.push_back(1);
divisors.push_back(num);
}
//You only need to check up to sqrt(num)
T topPossibleDivisor = ceil(sqrt(num));
for(uint64_t possibleDivisor = 1;possibleDivisor <= topPossibleDivisor;++possibleDivisor){
//Check if the counter evenly divides the number //Check if the counter evenly divides the number
//If it does the counter and the other number are both divisors //If it does the counter and the other number are both divisors
if((num % cnt) == 0){ if((num % possibleDivisor) == 0){
if(!isFound(cnt, divisors)){ //We don't need to check if the number already exists because we are only checking numbers <= sqrt(num), so there can be no duplicates
divisors.push_back(cnt); divisors.push_back(possibleDivisor);
} //We still need to account for sqrt(num) being a divisor
if(!isFound(num/cnt, divisors)){ if(possibleDivisor != topPossibleDivisor){
divisors.push_back(num / cnt); divisors.push_back(num / possibleDivisor)
} }
} }
} }
//Sort the vector for neatness
std::sort(divisors.begin(), divisors.end()); std::sort(divisors.begin(), divisors.end());
//Return the vector of divisors
return divisors; return divisors;
} }