From 77586965cae7b04c6f7ffd9e74dc75d77550b232 Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Thu, 31 Jan 2019 12:21:55 -0500 Subject: [PATCH] Updated the getDivisors funct to fix possible bugs and improve efficency --- Algorithms.hpp | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) 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; }