Python Program to Find the Factors of a Number
Beginner · Numbers
A factor of a number divides it exactly, with no remainder: the factors of 12 are 1, 2, 3, 4, 6 and 12. This program finds all the factors of a number by testing every number from 1 up to it.
Program
factors_of_a_number.py
num = 36 # or: num = int(input("Enter a positive number: "))
factors = []
for i in range(1, num + 1):
if num % i == 0: # no remainder, so i is a factor
factors.append(i)
print(f"Factors of {num}: {factors}")
print("Number of factors:", len(factors))
print("Sum of factors:", sum(factors))
Output
Factors of 36: [1, 2, 3, 4, 6, 9, 12, 18, 36] Number of factors: 9 Sum of factors: 91
How it works
- The loop tries every number
ifrom 1 tonum. num % iis the remainder after dividing, sonum % i == 0meansidividesnumexactly.- Each factor found is added to the
factorslist. len()counts the factors andsum()adds them up; 36 has 9 factors because it is a perfect square, and its middle factor 6 pairs with itself.
Other ways to write it
Faster: check up to the square root
Faster: check up to the square root
num = 36
factors = []
i = 1
while i * i <= num:
if num % i == 0:
factors.append(i)
if i != num // i: # 6 x 6: do not add 6 twice
factors.append(num // i)
i += 1
print(f"Factors of {num}: {sorted(factors)}")
Output
Factors of 36: [1, 2, 3, 4, 6, 9, 12, 18, 36]
Factors come in pairs, like 4 x 9 = 36, so finding the small one gives the big one too. Stopping at the square root makes this far faster for large numbers.
Using a list comprehension
Using a list comprehension
num = 100
factors = [i for i in range(1, num + 1) if num % i == 0]
print(f"Factors of {num}: {factors}")
Output
Factors of 100: [1, 2, 4, 5, 10, 20, 25, 50, 100]
A list comprehension builds the same list of factors in a single line.
Try it yourself
Use the number of factors to print whether the number is prime: a prime has exactly 2 factors.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises