Exercise 7
Write a Python program that returns the list of divisors of a given integer. Example if n = 36 , the algorithm returns the list [1, 2, 3, 6, 9, 18 , 36]
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def listDiv(n): # initialize the list of divisors of n l = [] # loop through integers 1 , 2 , 3 ,..., n for i in range(1, n+1): # if i is a divisor of n we add it to the list if n%i == 0: l.append(i) return l # Example n = 36 print("the list of divisors of n is: ", listDiv(n)) # The output is: the list of divisors of n is: [1, 2, 3, 4, 6, 9, 12, 18, 36] |
Younes Derfoufi
CRMEF OUJDA
1 thought on “Solution Exercise 7: Python algorithm that returns the list of divisors of a number”