Skip to content

Instantly share code, notes, and snippets.

@prophile
Created February 20, 2012 16:41
from math import sqrt
_LOW_PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23)
def factors(n):
# Get the basics out of the way
# Remove all the low factors in a loop
for p in _LOW_PRIMES:
while n % p == 0:
yield p
n //= p
if n == 1:
return
isqrt = int(sqrt(n))
for x in xrange(isqrt, _LOW_PRIMES[-1], -1):
if n % x == 0:
for f in factors(x):
yield f
for f in factors(n // x):
yield f
return
# Got here: it's prime
yield n
for i in xrange(1, 65536):
print "{0} = {1}".format(i, ' * '.join(str(f) for f in factors(i)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment