Python Output All Factors of a Positive Integer
In Python, we can write a simple program to find all factors of a positive integer. Factors are integers that can divide the number exactly. For example, the factors 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
print(f"The factors of {number} are: {find_factors(number)}")
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
return factors
number = 28
print(f"The factors of {number} are: {find_factors(number)}")
Code explanation:
find_factors(n)is a function used to find the integernall factors of.factors = []Initialize an empty list to store the found factors.for i in range(1, n + 1)Loop from 1 ton, check whether each number isna factor ofif n % i == 0Checkiwhether it can exactly dividen, if it can, theniYesna factor offactors.append(i)Add the found factors to the list.return factorsReturn the list containing all factors.number = 28Set the integer to find factors for.print(f"The factors of {number} are: {find_factors(number)}")Output the result.
Output result:
The factors of 28 are: [1, 2, 4, 7, 14, 28]Other Extensions
Python3 Examples