PythonMastery

Find the factors of a number in Python

List every factor of a number with a for loop and %, then a faster version that stops at the square root and finds the factors in pairs.

A factor (or divisor) of a number divides it with no remainder. The factors of 12 are 1, 2, 3, 4, 6 and 12.

The program

python
n = int(input("Enter a positive number: "))

factors = []
for i in range(1, n + 1):
    if n % i == 0:
        factors.append(i)

print(f"Factors of {n}: {factors}")
print(f"{n} has {len(factors)} factors")

Typed in this example: 36. Press Run to type your own.

output
Enter a positive number: 36
Factors of 36: [1, 2, 3, 4, 6, 9, 12, 18, 36]
36 has 9 factors

How it works

A number with exactly two factors (1 and itself) is prime. To split a number into its prime factors, see prime factors.

A faster way

Factors come in pairs: if i is a factor of n, then n // i is too. For 36 the pairs are 1 and 36, 2 and 18, 3 and 12, 4 and 9, and 6 and 6. So the loop only needs to go up to the square root of n:

python
import math


def factors(n):
    small = []
    large = []
    for i in range(1, math.isqrt(n) + 1):
        if n % i == 0:
            small.append(i)
            if i != n // i:
                large.append(n // i)
    return small + large[::-1]


print(factors(36))
print(factors(97))
print(len(factors(1_000_000)))
output
[1, 2, 3, 4, 6, 9, 12, 18, 36]
[1, 97]
49

Learn the idea: Loops: for, while, and the Pythonic Patterns, Functions & Scoping