mirror of
https://bitbucket.org/Mattrixwv/my-classes.git
synced 2025-12-06 18:23:57 -05:00
Updated the getDivisors funct to fix possible bugs and improve efficency
This commit is contained in:
@@ -196,20 +196,34 @@ std::vector<T> getFactors(T goalNumber){
|
||||
template<class T>
|
||||
std::vector<T> getDivisors(T num){
|
||||
std::vector<T> 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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user