How can we get all the divisors of a number?


#1

Question

In the context of this code challenge, how can we get all the divisors of a number?

Answer

Python does not include a built-in function to obtain all the divisors of a number, but you can do this fairly easily using a for loop and an if statement.

To find all the divisors of a number, we can utilize the modulo % operator, which returns the remainder after division. For any divisor of a number, the number modulo that divisor is always 0, because it evenly divides it. For example, 3 is a divisor of 12, because 12 % 3 = 0.

The structure of the loop would look something like this,

for i in range(1, number + 1):
  if number % i == 0:
    ...

In this code challenge, you can utilize the modulo operator in a similar way to find what numbers have the value 10 as a divisor.