Python Practice › Loop Programs › Program 34

Prime factors

MediumLoop Programs · 34 of 90

Write a Python program to find all prime factors of a number.

Advertisement
Input
360
Output
[2, 2, 2, 3, 3, 5]
[2, 3, 5]

Approach

  1. Divide by 2, 3, 4, … as many times as possible; every successful divisor is a prime factor.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs