Python Practice › Loop Programs › Program 34
Prime factors
Write a Python program to find all prime factors of a number.
Input
360
Output
[2, 2, 2, 3, 3, 5] [2, 3, 5]
Approach
- Divide by 2, 3, 4, … as many times as possible; every successful divisor is a prime factor.
Solution
n = 360factors = []d = 2while n > 1: while n % d == 0: factors.append(d) n //= d d += 1print(factors)print(sorted(set(factors)))Output
[2, 2, 2, 3, 3, 5] [2, 3, 5]
Line by line
Lines 5-7
The inner loop removes a factor completely (360 → 180 → 90 → 45 for d = 2).
Line 8
Composite divisors like 4 never match, because their prime parts were already removed.
Line 10
set gives the distinct prime factors.
Learn the concept
New to this topic? Read the lesson, then come back.