Python Print All Divisors of a Positive Integer
In Python, we can write a simple program to find all divisors of a positive integer. A divisor is an integer that divides the number evenly. For example, the divisors of 6 are 1, 2, 3, 6.
Example
def
find_factors
(
n
)
:
factors
=
[
]
for
i
in
range
(
1
,
n +
1
)
:
if
n % i
==
0
:
factors.
append
(
i
)
return
factors
number
=
28
(
f
"The factors of {number} are: {find_factors(number)}"
)
Code analysis:
find_factors(n)is a function used to find all divisors of the integern.factors = []Initialize an empty list to store the divisors found.for i in range(1, n + 1)Loop from 1 ton, checking whether each number isna divisor of the number.if n % i == 0ChecksiCheck whether it dividesnevenly; if it does, theniIsna divisor of the number.factors.append(i)Add the divisor found to the list.return factorsReturn the list containing all divisors.number = 28Set the integer whose divisors are to be found.print(f"The factors of {number} are: {find_factors(number)}")Print the result.
Output result:
The factors of 28 are: [1, 2, 4, 7, 14, 28]
Python3 Examples