Lesson 2 of 15
Prime Factorization
Prime Factorization
The Fundamental Theorem of Arithmetic states that every integer can be written uniquely as a product of prime numbers:
For example: , written as the sorted list [2, 2, 3, 5].
Trial Division
The simplest factorization algorithm tries dividing by each candidate divisor starting from 2. A key insight: if has no factor , then itself is prime.
def prime_factors(n):
factors = []
d = 2
while d * d <= n:
while n % d == 0:
factors.append(d)
n //= d
d += 1
if n > 1: # n is a remaining prime factor
factors.append(n)
return sorted(factors)
print(prime_factors(12)) # [2, 2, 3]
print(prime_factors(60)) # [2, 2, 3, 5]
How It Works
- Try dividing by up to
- Every time , append and divide by (repeat for repeated factors)
- After the loop, if , then is a prime — append it
The time complexity is , which is practical for numbers up to .
Counting with Multiplicity
The list returned includes each prime factor with repetition (multiplicity). For example:
- →
[2, 2, 3] - $36 = 2^2 \cdot 3^2
→[2, 2, 3, 3]`
Your Task
Implement prime_factors(n) that returns a sorted list of prime factors of with repetition.
Python runtime loading...
Loading...
Click "Run" to execute your code.