Python Output All Factors of a Positive Integer

Document 对象参考手册Python3 Examples

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)}")

Code explanation:

  1. find_factors(n)is a function used to find the integernall factors of.
  2. factors = []Initialize an empty list to store the found factors.
  3. for i in range(1, n + 1)Loop from 1 ton, check whether each number isna factor of
  4. if n % i == 0Checkiwhether it can exactly dividen, if it can, theniYesna factor of
  5. factors.append(i)Add the found factors to the list.
  6. return factorsReturn the list containing all factors.
  7. number = 28Set the integer to find factors for.
  8. 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]

Document 对象参考手册Python3 Examples

Other Extensions