it-Python-courses-python-string--Python-courses-python-exercises

Exercise7 || Solution

Write a Python algorithm that returns the list of divisors of a given integer. Example if n = 18, the algorithm returns the list [1, 2, 3, 6, 9, 18]

Solution

def listDiv (n):
# initialization of the divisors list of n
l = []
# iterate over 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 = 18
print ("the divisors list of n is:", listDiv (n))
# The output is: the divisors list of n is: [1, 2, 3, 6, 9, 18]

Younes Derfoufi
my-courses.net

Leave a Reply