Having recently taught a kid I know prime factorization, the algorithm is trivial provided you have a list of primes.
- Starting with 2, divide that into the target as many times as it can and leave zero remainder.
- Take the next prime (3) and divide that into the target as in step one
- Write down each factor you found and repeat until you run out of remainder.
Added, per request, algorithmic pseudo-code:
def factor(n):
"""returns a list of the prime factors of n"""
factors = []
p = primes.generator()
while n > 1:
x = p.next()
while n % x == 0:
n = n / x
factors.append(x)
return factors
Where successive calls to p.next()
yields the next value in the series of primes {2, 3, 5, 7, 11, ...}
Any resemblance of that pseudo-code to actual working Python code is purely coincidental. I probably shouldn't mention that the definition of primes.generator()
is one line shorter (but one line is 50 characters long). I originally wrote this "code" because the GNU factor
program wouldn't accept inputs where log2(n) >= 40.