用于Collat​​z猜想的Python递归函数

时间:2017-03-02 00:11:11

标签: python recursion

我编写了以下递归程序,以显示一个数字在Collat​​z猜想中经过的步数:

def cycle_length(n):
    count = 0
    if n == 1:
        return count
    if n%2 == 0:
        count += cycle_length(int(n/2)) +1
    elif n%2 != 0:
        count += cycle_length(int(3*n+1)) + 1
        print("The count is: ",count)
    return count 

print(cycle_length(22))

然而,当它应该是16时,计数是15.但是,当我将初始计数更改为1或说:

return count + 1

它将计数翻倍至31.我无法弄清楚造成这种情况的原因。

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

n为1时,您需要将count递增1才能返回。

def cycle_length(n):
    count = 0
    if n == 1:
        return count + 1 # or simply return 1
    ...

但是如果您不选择计算第0步,我认为您的代码在语法上是正确的。

请参阅http://oeis.org/A070165

答案 1 :(得分:0)

当你使count = 1时,你不应该在后面的if,else if语句中使用count + =。此外,在我看来,你之前的回答已经正确。但是,如果要向其添加1(即计算1发生时的步骤),请执行以下操作:

 def cycle_length(n):
    count = 1
    if n == 1:
        return count
    if n%2 == 0:
        count = (cycle_length(int(n/2)) +1)
    elif n%2 != 0:
        count = (cycle_length(int(3*n+1)) + 1)
    return count

答案 2 :(得分:0)

Collat​​z序列始终以给定的数字开头,因此您的基本情况应该返回1

话虽如此,您也可以使用迭代计算它,因为python不太喜欢递归,例如您的代码无法计算9780657631或75128138247而不会出现递归错误

这里是迭代版

def collatz_length(n):
    if n<1:
        raise ValueError
    count = 1
    while n != 1:
        if n%2 == 0:
            n = n//2
        else:
            n = 3*n+1
        count += 1
    return count
相关问题