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