【发布时间】:2019-01-21 18:11:43
【问题描述】:
我用 Python3 编写了一个计算 Collatz 猜想的基本脚本。它需要一个正整数作为输入,并返回步数,直到序列下降到 1。
我的脚本非常适合小于~2 万亿的任何整数输入,但高于此阈值的输出太小了。
例如,这里有一些输入、我的脚本的输出和实际正确的输出:
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 万亿的输入,我的脚本输出总是比正确输出少 1,052,但我不知道是什么原因造成的。
谁能解释问题出在哪里,以及如何更新/修复脚本以使其适用于所有输入?我认为 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")
【问题讨论】:
-
欢迎使用电脑! :D
标签: python python-3.x algorithm iteration collatz