1

我有一个(可能是笨拙的)函数来找到一个数字的最大素数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)
4

1 回答 1

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)
于 2013-10-18T07:38:39.843 回答