def is_prime(n): """Returns True if n is a prime-number.""" if n==1: return False if n<4: return True # 2 and 3 are prime if n%2==0: return False if n<9: return True # We have already excluded 4, 6 and 8. if n%3==0: return False for i in xrange(5, int(n**.5)+1, 6): if n%i==0: return False if n%(i+2)==0: return False return True # In all other cases class prime_iterator: def __init__(self, maxcount=0, maxnum=0): self.maxcount = maxcount self.maxnum = maxnum self.count = 0 self.num = 0 def next(self): if self.num==2: self.num+=1 return 3 self.num+=2 while not is_prime(self.num): self.num+=2 self.count += 1 if self.maxcount and self.count >= self.maxcount: raise StopIteration if self.maxnum and self.num >= self.maxnum: raise StopIteration return self.num def reset(self): self.num = 2 def __iter__(self): return self def prime_factors(n): """Returns a list of all the prime factors of n.""" if is_prime(n): return [n] iter = prime_iterator() i = iter.next() while n % i != 0: i = iter.next() return [i] + prime_factors(n/i)