I've written a basic script in Python3 that calculates the Collatz Conjecture. It takes a positive integer as an input and returns the number the steps until the sequence drops down to 1.
My script works perfectly for any integer inputs less than ~2 trillion, but above this threshold the outputs are too small.
As an example, here are some inputs, my script's output, and the actual correct output:
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 `
Correct output values are based on this link: http://www.ericr.nl/wondrous/delrecs.html
My script's output is always exactly 1,052 less than the correct output for inputs above 2 trillion, but I have no idea as to what's causing this.
Can anyone explain what's wrong, and how to update/fix the script so that it works correctly for all inputs? I thought Python is able to accept arbitrarily big numbers without a problem ...
Thank you!
# 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")