[英]Python find sum of prime factors without loop
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
但是,如果 prime_factor(m, k) 的结果大于 2,则在 factor=prime_factor(m, k) 后转到 main(n) 时,factor 将为 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.您的
prime_factor
函数对递归调用的结果没有做任何事情。 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.也是次要的优化,但您可以调整您的值,以便从 3 开始并在递归调用中执行 prime_factor(m, k+2) 而不是 k+1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.