Added a function to return the divisors of a number

This commit is contained in:
2019-01-31 12:10:51 -05:00
parent ad7a69ebc4
commit e9fa256b98

View File

@@ -118,3 +118,30 @@ def getFactors(goalNumber: int):
#Return the list of factors
return factors
#This function returns all the divisors of goalNumber
def getDivisors(goalNumber: int) -> list:
divisors = []
#Start by checking that the number is positive
if(goalNumber <= 0):
return divisors
#If the number is 1 return just itself
elif(goalNumber == 1):
divisors.append(1)
#Otherwise add 1 and itself to the list
else:
divisors.append(1)
divisors.append(goalNumber)
#Start at 3 and loop through all numbers < (goalNumber / 2 ) looking for a number that divides it evenly
topPossibleDivisor = math.ceil(math.sqrt(goalNumber))
for possibleDivisor in range(2, topPossibleDivisor + 1): #Add one because we need <= goalNumber/2
#If you find one add it and the number it creates to the list
if((goalNumber % possibleDivisor) == 0):
divisors.append(possibleDivisor)
divisors.append(goalNumber / possibleDivisor)
#Sort the list before returning for neatness
divisors.sort()
#Return the list
return divisors