我有一个(可能是笨拙的)函数来找到数字n
的最大素数因子(下图)。
def largest_prime_factor(n,factor=2):
if n % factor == 0:
if n == factor:
return factor
else:
largest_prime_factor(n/factor,factor)
else:
largest_prime_factor(n,factor+1)
#Printing function output
print largest_prime_factor(600)
但是当我尝试打印函数的返回输出时,它只是说None
。但是,当我让函数打印其输出(如下)时,它会输出正确的答案(5)。我在上面的片段中做错了什么?
def largest_prime_factor(n,factor=2):
if n % factor == 0:
if n == factor:
print factor #Printing, not returning
else:
largest_prime_factor(n/factor,factor)
else:
largest_prime_factor(n,factor+1)
#Calling the function
largest_prime_factor(600)
答案 0 :(得分:2)
你错过了一些回复电话:
def largest_prime_factor(n,factor=2):
if n % factor == 0:
if n == factor:
return factor
else:
return largest_prime_factor(n/factor,factor)
else:
return largest_prime_factor(n,factor+1)