mirror of
https://bitbucket.org/Mattrixwv/luaclasses.git
synced 2025-12-06 18:33:59 -05:00
Added a function to get all divisors of a number
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user