10/12/2024

This is just a fun little piece of code I made a while back I never got to share. 3n+1, or better known as the Collatz conjecture is a mathematical hypothesis that states for any positive integer, if you repeatedly divide it by 2 when it’s even or multiply it by 3 and add 1 when it’s odd, you will eventually reach the number 1. Despite its simplicity, it has not been proven or disproven for all integers.

If this peeks your interest, you can read more about it over on Wikipedia

Now, without further ado, Lets look at the code.


while True:
    number = float(input("number = "))
    print("=== solving ===")

    while number != 0:

        if number % 2 == 0:
            number = number / 2
        else:
            number = number * 3 + 1

        if number == 1:
            break
        if number == float('inf'):

            print("infinite number, please select another")
            break
        print(number)

As you can see, it’s fairly simple and mostly just consists of basic math and if/else statements. The program works by taking a number input from the user and repeatedly applying operations based on whether the number is even or odd. If the number is even, it is divided by 2; if it’s odd, it is multiplied by 3 and increased by 1. After each operation, the program checks whether the number has reached 1, in which case it stops the process. If the number somehow becomes infinite (which is unlikely with normal inputs), it alerts the user and asks for a new number. The program continuously prints the resulting number after each step, showing the progression of the sequence.