I tried to print a factor of a number using Python. ie if input value is 24
then the output is [1,2,2,2,3]
(1*2*2*2*3=24).
But the answer of the below program is [1,2,3,2,2,2,2]
instead of [1,2,3,2,2]
def is_prime(i):
for j in range(2,i+1):
if(i%j==0):
break
if(i==j):
return 1
else:
return 0
def fact(a):
i=2
while(i<=a):
if(a%i==0):
if(is_prime(i)):
li.append(i)
a=int(a/i)
if(a==1):
return
else:
fact(a)
i=i+1
if(a>=2):
fact(a)
return
li=[]
li.append(1)
a=int(input())
fact(a)
print(li)
The problem is the recursive call:
while(i<=a):
if(a%i==0):
if(is_prime(i)):
li.append(i)
a=int(a/i)
if(a==1):
return
else:
fact(a) # <-- problem
i=i+1
This will call fact
again for any non-prime factor of a
, like 4
, 6
, 8
or 12
in the case of 24
. And those calls will again add 2
to the (global) list of results. Instead, remove the recursive call and just continue with the loop. Also, you should change the outermost if
to while
so multiple of the same factor can be found.
Also, the call to is_prime
is redundant, as i
is already guaranteed to be prime (otherwise a
would have already been divided by one of i
's prime factors), and the return
is redundant, too. Finally, for this function to be applicable more than just once, I strongly suggest moving the declaration of li
inside the function and returning it at the end.
def fact(a):
li = [1] # actually, 1 is not a prime factor, though
i = 2
while i <= a:
while a % i == 0:
li.append(i)
a = a // i
i += 1
return li
li = fact(a)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.