From 54b8f3c5f0cb4cba0dd21134e48e4d0af542102b Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Thu, 7 Feb 2019 11:43:34 -0500 Subject: [PATCH] Added a function to get all divisors of a number --- Algorithms.lua | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/Algorithms.lua b/Algorithms.lua index b93c27f..87c0aae 100644 --- a/Algorithms.lua +++ b/Algorithms.lua @@ -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