import math
import sys
def factor(number):
"""
Return list of prime factors for 'number'.
"""
factors = []
limit = int(math.sqrt(number))
limit = limit if limit > 3 else 3
primes = create_primes_generator(limit)
for p in primes:
while number % p == 0:
number /= p
factors.append(p)
if number == 1:
break
return factors if factors else [number]
def create_primes_generator(limit):
"""
Return prime numbers up to 'limit'.
"""
if limit < 2:
raise ValueError("Limit must be an integer 2 or larger.")
# Cheat a bit, since we know that, other than 2, no other primes are even.
yield 2
pool = range(1, limit + 1, 2)[1: ]
while (len(pool)):
prime = pool[0]
multiples = []
# The sieve of Eratosthenes.
for i in pool:
if i % prime == 0:
multiples.append(i)
pool = set(pool)
pool = pool.difference(set(multiples))
pool = sorted(pool)
yield prime
def main(number):
"""
Arg 1 must be a positive integer.
"""
factors = factor(number)
print ', '.join([str(f) for f in factors])
if __name__ == '__main__':
number = sys.argv[1]
try:
number = int(number)
main(number)
except Exception, e:
print "Error: %s" % (e)
print "Usage: python sieve.py positive_number"