Having recently trained a child, I know the basic factorization, the algorithm is trivial if you have a list of primes.
- Starting at 2, divide this by the target as many times as you can, and leave zero balance.
- Take the following simple (3) and divide it into a target, as in the first step
- Record each found factor and repeat until you finish the remainder.
Algorithmic pseudocode added for each request:
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
If consecutive calls to p.next() give the following value in a series of primes {2, 3, 5, 7, 11, ...} Any similarity between this pseudo-code and the actual working Python code is purely random. I probably shouldn't mention that the definition of primes.generator() is one line shorter (but one line 50 characters long). I originally wrote this βcodeβ because the GNU factor program did not accept input, where log 2 (n)> = 40.
msw
source share