Python Program to Find Prime Factors of a Number
while n % i == 0: factors.append(i); n //= i.Examples
How to Think About It
Algorithm
Code
def prime_factors(n): factors = [] i = 2 while i * i <= n: while n % i == 0: factors.append(i) n //= i i += 1 if n > 1: factors.append(n) return factors num = 28 print(prime_factors(num))
Dry Run
Let's trace the number 28 through the code to find its prime factors.
Initialize variables
n = 28, factors = [], i = 2
Check if i*i <= n
2*2=4 <= 28 is True
Check if n % i == 0
28 % 2 == 0 is True, add 2 to factors, n = 28 // 2 = 14
Repeat inner while
14 % 2 == 0 is True, add 2 to factors, n = 14 // 2 = 7
Repeat inner while
7 % 2 == 0 is False, exit inner loop
Increment i
i = 3
Check i*i <= n
3*3=9 <= 7 is False, exit outer loop
Check if n > 1
n = 7 > 1 is True, add 7 to factors
| i | n | factors |
|---|---|---|
| 2 | 28 | [] |
| 2 | 14 | [2] |
| 2 | 7 | [2, 2] |
| 3 | 7 | [2, 2] |
| - | 7 | [2, 2, 7] |
Why This Works
Step 1: Start with smallest divisor
We begin checking divisors from 2 because it is the smallest prime number.
Step 2: Divide repeatedly
If the number divides evenly by the divisor, we record it and divide the number to reduce it.
Step 3: Stop when divisor squared exceeds number
We only need to check divisors up to the square root of the number because larger factors would have appeared earlier.
Step 4: Add remaining number if prime
If after division the number is still greater than 1, it means it is a prime factor itself.
Alternative Approaches
def prime_factors_recursive(n, i=2, factors=None): if factors is None: factors = [] if i * i > n: if n > 1: factors.append(n) return factors if n % i == 0: factors.append(i) return prime_factors_recursive(n // i, i, factors) else: return prime_factors_recursive(n, i + 1, factors) print(prime_factors_recursive(28))
from sympy import primefactors print(primefactors(28))
Complexity: O(√n) time, O(log n) space
Time Complexity
The outer loop runs up to the square root of n, and the inner loop divides n by prime factors, making the overall time roughly O(√n).
Space Complexity
The space used is for storing factors, which is at most O(log n) because the number of prime factors grows slowly.
Which Approach is Fastest?
Using the sympy library is fastest for large numbers, but the manual loop method is simple and requires no extra packages.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop division | O(√n) | O(log n) | Learning and small to medium numbers |
| Recursion | O(√n) | O(log n) | Elegant code but limited by recursion depth |
| sympy library | Optimized C code | Depends on implementation | Fastest for large numbers, requires external library |