我已经用Python3编写了一个基本脚本来计算Collatz猜想.它将一个正整数作为输入,并返回步数,直到序列降为1.
我的脚本适用于任何整数输入less than ~2 trillion,但高于此阈值时,输出太小.
例如,以下是一些输入、脚本的输出和实际正确的输出:
Integer Input Script Output Correct Output
989,345,275,647 1,348 1,348
1,122,382,791,663 1,356 1,356
1,444,338,092,271 1,408 1,408
1,899,148,184,679 1,411 1,411
2,081,751,768,559 385 1,437
2,775,669,024,745 388 1,440
3,700,892,032,993 391 1,443
3,743,559,068,799 497 1,549 `
正确的输出值基于以下链接:http://www.ericr.nl/wondrous/delrecs.html
对于2万亿以上的输入,我的脚本的输出总是比正确的输出少1052,但我不知道是什么导致了这一点.
有人能解释一下哪里出了问题,以及如何更新/修复脚本,使其能够正确地用于所有输入吗?我认为Python能够毫无问题地接受任意大的数字...
非常感谢.
# Python Code for the Collatz Conjecture
# Rules: Take any integer 'n' and assess:
# If integer is even, divide by 2 (n/2)
# If integer is odd, multiply by 3 and add 1 (3n+1)
# Result: a list of all steps until 'n' goes down to 1
while True:
print("Please enter a positive integer:")
n = input("")
if n == 'q':
print("Until next time ...\n")
break
try:
n = int(n)
if n > 0:
i = 0
while n > 1:
if n % 2 == 0:
n = int(n/2)
i += 1
else:
n = int((3*n)+1)
i += 1
print("# of steps to reach '1' = ", str(i), "\n")
else:
print("Sorry, that's not a valid entry. Please try again!\n")
except ValueError:
print("Sorry, that's not a valid entry. Please try again!\n")