I'm trying to write a python code to find the prime factors of any given number
def pf(n):
for i in range(2,n):
if n%i==0: #find the factors
for j in range(2,i): #check if the factor is prime
if i%j==0:
break
else: #find the prime ones
print(i)
My problem is that this code works fine with small numbers however with big numbers i have to interrupt the execution
for example:
pf(600851475143)
71
839
1471
6857
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
pf(600851475143)
File "<pyshell#1>", line 2, in pf
for i in range(2,n):
KeyboardInterrupt
the prime factors of this big number were found in less than a second, so my question is how to tweak this code to stop unnecessary iterations after finding the factors with the use of the for not the while loop
You can speed things up by dividing
n
by the obtained value in each iteration step. This way you decrease the number you are iterating. I would implement something like this (not yet sure if this is optimal and results in the lowest number of operations):Note, if using the improvement of looping until the root of the number we omit the case that the number itself is a prime number. However, if the function does not result any prime factors it is save to assume that the input is a prime number itself.
The
return
statements stop the main loop (and the function) after the recursive call. So each call of the function only results in one value and a call for the function on the result of the division of the number by its found prime.If you make a set with all the prime numbers and check if the value is in this set you will win some time, instead of looping over all values.
Compared to the non-recursive solution by jonrsharpe this one is almost four times as fast:
The implementation is limited by the overflow limit of
range()
, which results in an overflow for the input value(600851475143**2)+1
. More details on the maximum size forrange
can be found in this question: Python: Range() maximum size; dynamic or static?A possible issue with this solution could be that the maximum recursion depth is achieved. For more details on that visit this question: Maximum recursion depth