I am trying to build a small program to test the collatz’s hypothesis. So far, I have the following:
c0 = int(input("Enter an integer and non-zero number"))
steps = 0
while c0 != 1:
if c0%2:
c0 = c0/2
steps += 1
elif c0%2 !=0:
c0= (3*c0) + 1
steps += 1
print (c0)
print (steps)
But when I run it, it’s going into an endless loop of 0.0s. Not really getting where the problem is.
Advertisement
Answer
As Nearoo mentioned, c0 % 2 is the same as c0 % 2 != 0 because 1 (when c0 is odd, ‘c0 % 2’ is 1) has a boolean value of True.
Here’s the correct solution:
n = int(input("Enter a strictly positive integer: "))
steps = 0
while n != 1:
if n % 2 == 0:
n = n / 2
elif n % 2 == 1:
n = (3*n) + 1
steps += 1
print(int(n))
print (steps)