The following functional program factors an integer by trial division. I am not interested in improving the efficiency (but not in decreasing it either), I am interested how it can be made better or neater using functional constructions. I just seem to think there are a few tweaks to make this pattern more consistent and tight (this is hard to describe), without turning it into boilerplate.
def primes(limit): return (x for x in xrange(2,limit+1) if len(factorization(x)) == 1) def factor(factors,p): n = factors.pop() while n % p == 0: n /= p factors += [p] return factors+[n] if n > 1 else factors def factorization(n): from math import sqrt return reduce(factor,primes(int(sqrt(n))),[n])
It would be great if it could all fit on one line or into two functions that looked a lot tighter -- I'm sure there must be some way, but I can not see it yet. What can be done?