Reputation: 57
So while Wikipedia surfing, I stumbled onto the Collatz Conjecture So I decided to write a simple python program,
while True:
x = int(input("Enter a number: "))
n=0
while True:
if (x % 2) == 0:
x = x/2
n += 1
print(x)
else:
x = 3*x +1
n+=1
print(x)
if x == 1:
break
print("N = %d" %(n))
At first I played around with random numbers, and then I decided to test some of the larger numbers that the Wikipedia article represents. The program worked perfectly up until 75,128,138,247 on Wikipedia's " Examples" Section,previously it matched the number of steps exactly, and then it just randomly says "512" for N (the number of steps. I just don't understand why. Can anyone Help?
Upvotes: 1
Views: 79
Reputation: 80232
Float division might cause issues (note output as floats), so work in integers:
change
x = x/2
to integer division (your print
correponds to Python 3, so it is available)
x = x // 2
Upvotes: 2