I recently made a piece of code in Python that takes a user inputted number "n" and prints the prime factors of that number, including repeating primes. I got super excited cause I've been working on this for a while, but in reality it doesn't work so well. Any n larger than about 500,000 takes so long to factor and I want to know if there is any way to optimize it.
import sys
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if not n & 1:
return False
for x in range(3,int(n**0.5)+1,2):
if n % x == 0:
return False
return True
def factors(n):
n = int(n)
factors = []
test_numbers = []
if is_prime(n) == True:
print "%s is prime!" % n
else:
for a in range(1,n+1):
if is_prime(a) == True:
test_numbers.append(a)
while int(len(test_numbers)) > 0:
mx = int(max(test_numbers))
while n % mx == 0:
n = n/mx
factors.append(mx)
else:
test_numbers.remove(mx)
print factors
n = raw_input("What number would you like to factorize? ")
factors(n)
print
thing = raw_input("Press ENTER to continue.")
sys.exit()
Here are a couple of improvements using some Pythonic idioms such as list comprehension:
It will be fast or slow depending on how many factors
n
has (slowest ifn
is prime, fastest if it has lots of small prime factors).