RosettaCodeData/Task/Factors-of-an-integer/Python/factors-of-an-integer-4.py
2015-02-20 00:35:01 -05:00

18 lines
557 B
Python

from itertools import chain, cycle, accumulate # last of which is Python 3 only
def factors(n):
def prime_powers(n):
# c goes through 2, 3, 5, then the infinite (6n+1, 6n+5) series
for c in accumulate(chain([2, 1, 2], cycle([2,4]))):
if c*c > n: break
if n%c: continue
d,p = (), c
while not n%c:
n,p,d = n//c, p*c, d + (p,)
yield(d)
if n > 1: yield((n,))
r = [1]
for e in prime_powers(n):
r += [a*b for a in r for b in e]
return r