I'm trying to produce the sum of all prime factors of a number without using loop. However if the result of prime_factor(m, k) bigger than 2, when go to main(n) after factor=prime_factor(m, k), factor will be None
def prime_factor(m, k):
if m%k==0:
return k
else:
prime_factor(m, k+1)
def main(n):
if n<2:
return 0
if n==2:
return n
else:
factor=prime_factor(n, 2)
return factor+main(n//factor)
Your prime_factor
function is not doing anything with the result of the recursive call. You need to return it:
def prime_factor(m, k):
if m%k==0:
return k
else:
return prime_factor(m, k+1) # need the return here
Also minor optimization but you could adjust your values so you start at 3 and do prime_factor(m, k+2) in the recursive call instead of k+1.
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.