Added a function to get all divisors of a number

This commit is contained in:
Matthew Ellison
2019-02-07 11:43:34 -05:00
parent 7bec0bd1c7
commit 54b8f3c5f0

View File

@@ -136,3 +136,35 @@ function getFactors(goalNumber)
--Return the list of factors
return factors;
end
function getDivisors(goalNumber)
local divisors = {};
--Start by checking that the number is positive
if(goalNumber <= 0) then
return divisors;
--If the number is 1 return just itself
elseif(goalNumber == 1) then
divisors[#divisors+1] = 1;
--Otherwise add 1 and itself to the list
else
divisors[#divisors+1] = 1;
divisors[#divisors+1] = goalNumber;
end
--Start at 3 and loop through all numbers < (goalNumber / 2) looking for a number that divides it evenly
local topPossibleDivisor = math.ceil(math.sqrt(goalNumber));
for possibleDivisor=2,topPossibleDivisor do
--If you find one add it and the number it creates to the list
if((goalNumber % possibleDivisor) == 0) then
divisors[#divisors+1] = possibleDivisor;
--Account for the possibility of sqrt(goalNumber) being a divisor
if(possibleDivisor ~= topPossibleDivisor) then
divisors[#divisors + 1] =(goalNumber / possibleDivisor);
end
end
end
--Sort the list before returning for neatness
table.sort(divisors);
--Return the list
return divisors;
end