问题
I'm trying to create a program for prime factorization of a number and this is the code I came up with.
def primeFactors(n):
l=[]
ss=0
for i in range(2,n,1):
#checking for prime
t=0
for j in range(2,i):
if(i==2):
continue
if(i%j==0):
t=t+1
if(t>0):
continue
else:
if(n==0):
break
else:
print(i)
if(n%i==0):
n=n//i
ss=ss+1
i=i-1
if(n%i!=0 and ss>0):
l.append(i)
l.append(ss)
ss=0
else:
continue
q=""
for i in range(0,len(l),2):
q=q+"("+str(l[i])+"**"+str(l[i+1])+")"
return q
The working of the code is as follows:
- It checks whether the number in the outer loop is a prime or not.
- If it is a prime, then it proceeds to check whether division of the number with
n
would yield a remainder of 0 or not, if it does, divide it. - Increment
ss
which is the number of times the prime number would be used in the whole factorisation. Also, decrement the value ofi
so that when it increments at the end of the loop, it remains the same to check again whetheri
can dividen
or not. - If it cannot divide and
ss
(number of timesi
could divide) is more than 0 then we append it to a list.
I am getting timeout errors in this and cannot figure out how to go about fixing it.
Any help is appreciated
回答1:
You can increase i
only if i
does not divide n.
Also, you can just check until the square root of n
, since if i
divides n
, then i <= sqrt(n)
.
Example:
import math
def prime_factors(n):
i, factors = 2, []
while n > 1 and i <= int(math.sqrt(n)):
if n%i == 0:
n/=i
factors.append(i)
else:
i+=1
if n > 1:
factors.append(int(n))
return factors
>>> prime_factors(64)
[2, 2, 2, 2, 2, 2]
>>> prime_factors(28)
[2, 2, 7]
>>> prime_factors(31)
[31]
Note. You don't need to check if i
is a prime number. i
cannot be not prime, since if i
were not prime, then there would exist a j < i
that divides i
with j
being prime. Since i
goes from 2
to sqrt(n)
, it would have met before in the loop.
来源:https://stackoverflow.com/questions/59961109/prime-factorization-of-a-big-number