直接搜索,为避免重复计算,我们用一个字典来存放已计算过的数字及其序列长度。结果是 $837799$ (长度为$525$)。
collatzDict={1:1, 2:2, 4:3, 8:4, 16:5, 32:6, 64:7, 128:8, 256:9, 512:10, 1024:11, 2048:12, 4096:13, 8192:14, 16384:15, 32768:16, 65536:17, 131072:18, 262144:19, 524288:20}
maxSeq=0
maxN=0
for i in range(1000000):
m=i+1
iSeq=[m]
step=0
while m not in collatzDict:
if m%2==0:
m=m/2
else:
m=3*m+1
iSeq.append(m)
step=step+1
for j in iSeq:
collatzDict[j]=collatzDict[m]+step
step=step-1
if collatzDict[i+1]>maxSeq:
maxSeq=collatzDict[i+1]
maxN=i+1
print maxSeq, maxN
|