# Collat z猜想Python-不正确的输出超过2万亿(仅!)

## python-3.x algorithm (1)

``n = int(n/2)``

...将`n`转换为float，将float除以2，然后通过丢弃小数部分将其转换回int。

``n = n // 2``

``````>>> n = 2**53 + 3
>>> n
9007199254740995
>>> int(n/2)
4503599627370498
>>> n//2
4503599627370497``````

``````def collatz(n):
overflow = False
i = 0
while n > 1:
if n > 2**53:
overflow=True
if n % 2 == 0:
n = int(n/2)
i += 1
else:
n = int((3*n)+1)
i += 1
return i, overflow

if __name__ == '__main__':
import sys
for arg in sys.argv[1:]:
num = int(arg.replace(',', ''))
result, overflow = collatz(num)
print(f'{arg:>30}: {result:10,} {overflow}')``````

``\$ python3 collatz.py 989,345,275,647 1,122,382,791,663 1,444,338,092,271 1,899,148,184,679 2,081,751,768,559 2,775,669,024,745 3,700,892,032,993 3,743,559,068,799``

......它给了我：

``````           989,345,275,647:      1,348 False
1,122,382,791,663:      1,356 False
1,444,338,092,271:      1,408 False
1,899,148,184,679:      1,411 False
2,081,751,768,559:        385 True
2,775,669,024,745:        388 True
3,700,892,032,993:        391 True
3,743,559,068,799:        497 True``````

``````           989,345,275,647:      1,348 False
1,122,382,791,663:      1,356 False
1,444,338,092,271:      1,408 False
1,899,148,184,679:      1,411 False
2,081,751,768,559:      1,437 True
2,775,669,024,745:      1,440 True
3,700,892,032,993:      1,443 True
3,743,559,068,799:      1,549 True``````

``````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 ```````

``````# 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:
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")``````