diff --git a/Algorithms.hpp b/Algorithms.hpp index dca330a..3dd21b7 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -196,20 +196,34 @@ std::vector getFactors(T goalNumber){ template std::vector getDivisors(T num){ std::vector divisors; //Holds the number of divisors - //You only need to go to sqrt(number). cnt * cnt is faster than sqrt() - for(uint64_t cnt = 1;cnt * cnt <= num;++cnt){ + //Ensure the parameter is a valid number + 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 //If it does the counter and the other number are both divisors - if((num % cnt) == 0){ - if(!isFound(cnt, divisors)){ - divisors.push_back(cnt); - } - if(!isFound(num/cnt, divisors)){ - divisors.push_back(num / cnt); + if((num % possibleDivisor) == 0){ + //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(possibleDivisor); + //We still need to account for sqrt(num) being a divisor + if(possibleDivisor != topPossibleDivisor){ + divisors.push_back(num / possibleDivisor) } } } + //Sort the vector for neatness std::sort(divisors.begin(), divisors.end()); + //Return the vector of divisors return divisors; }