Prime Factors of Number

Find all prime factors of a number.

AdvancedPhase 6 - Category 3: Loop & Conditional MixExample 6 of 10
prime-factors-of-number.py
1# Helper function
2def is_prime(n):
3 if n < 2:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10# Take number
11num = int(input("Enter a number: "))
12
13# Find prime factors
14print(f"Prime factors of {num}:")
15factors = []
16for i in range(2, num + 1):
17 if num % i == 0 and is_prime(i):
18 factors.append(i)
19
20print(factors)

Output

Enter a number: 60
Prime factors of 60:
[2, 3, 5]

What's going on

Find factors and check if prime.

Key Concepts:

Find all factors
Check if factor is prime
Collect prime factors