DEV Community

Isaac
Isaac

Posted on

Lothar Collatz hypothesis

In 1937, a German mathematician named Lothar Collatz formulated an intriguing hypothesis (it still remains unproven) which can be described in the following way:

1.Take any non-negative and non-zero integer number and name it c0.
2.If it's even, evaluate a new c0 as c0 ÷ 2.
3.Otherwise, if it's odd, evaluate a new c0 as 3 × c0 + 1.
4.If c0 ≠ 1, skip to point 2.

The hypothesis says that regardless of the initial value of c0, it will always go to 1:

print("Prove that Lothar Collatz  is wrong!!!!")
c0 = int(input('Enter a non- negative, non-zero integer: '))
step = 0
while c0 != 1:
    if c0 % 2 == 0:
        c0 //= 2
        if c0 != 1:
            step += 1
            print(' New value is ', c0)
            continue
        elif c0 == 1:
            step += 1
            print(' New value is ', c0)
            break
    elif c0 % 2 == 1:
        c0 = c0 * 3 + 1
        if c0 != 1:
            step += 1
            print(' New value is ', c0)
            continue

print('Total Steps: ', step)
print("*"*44)
print("*"*44)
Enter fullscreen mode Exit fullscreen mode

As you can see we have transform the whole Collatz idea in to a while loop that print every step needed to achieve the goal.
At the end we run a for loop with a sleep command to avoid the program to close abruptly after doing the calculations:

import time

for i in range(1,11):
    time.sleep(1)

print("*"*44)
print("*"*44)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)