可以帮助我解决最长Collat​​z序列-14

时间:2020-05-19 18:07:31

标签: python

这是我的代码

def Collatz(n,x,m):    
    if(n%2!=0):
        n=3*n+1
        x=x+1
        Collatz(n,x,m)   
    else:
        n=n/2
        x=x+1
        if(n==1):
            sumlist.append(x)
            print(sumlist)
            print(m)
            m=m+1
            if m==1000000:
                print(max(sumlist),"bye")
                exit();
            Collatz(m,0,m)
        Collatz(n,x,m)            
sumlist=[]

c=2

Collatz(c,0,2)

我的代码是这个。但是执行它后会出现一些错误。

1]
2
[1, 7]
3
[1, 7, 2]
4
[1, 7, 2, 5]
5
[1, 7, 2, 5, 8]
6
[1, 7, 2, 5, 8, 16]
7
[1, 7, 2, 5, 8, 16, 3]
8
[1, 7, 2, 5, 8, 16, 3, 19]
9
[1, 7, 2, 5, 8, 16, 3, 19, 6]
10
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14]
11
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9]
12
[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9]
13.....
.....[1, 7, 2, 5, 8, 16, 3, 19, 6, 14, 9, 9, 17, 17, 4, 12, 20, 20, 7, 7, 15, 15, 10, 23, 10, 111, 18, 18, 18, 106, 5, 26, 13, 13, 21, 21, 21, 34, 8, 109, 8, 29, 16, 16, 16, 104]
47
Traceback (most recent call last):
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 61, in <module>
    Collatz(c,0,2)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 54, in Collatz
    Collatz(m,0,m)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 36, in Collatz
    Collatz(n,x,m)
  File "C:\Moratuwa Engineering Study Materials\projecteuler\projecteuler questions.py", line 56, in Collatz

此代码将一直运行到m = 47为止。然后显示错误。 谁能帮我?

1 个答案:

答案 0 :(得分:0)

一个短期解决方案是将Python的默认递归深度从1000手动提高到更高的数值:

import sys
sys.setrecursionlimit(20000)

def Collatz(n,x,m):  
    ...

从中期来看,您应将if(n==1): 内部的代码移入程序的主循环。在m上进行的迭代不属于Collatz函数,这就是为什么您的调用堆栈越来越递归并且永远不会被清除的原因。