// python projects

Collatz Conjecture in Python

The Collatz Conjecture, also known as the 3(x) + 1 conjecture, is a famous unsolved problem in mathematics. It proposes a sequence defined by the following rules: Start with any positive integer x. If x is even, divide it by 2; if n is odd, multiply it by 3 and add 1. The conjecture posits that no matter the starting number, the sequence will eventually reach the value 1.

2021 1 min read pythonmath

The Collatz Conjecture, also known as the 3(x) + 1 conjecture, is a famous unsolved problem in mathematics. It proposes a sequence defined by the following rules: Start with any positive integer x. If x is even, divide it by 2; if n is odd, multiply it by 3 and add 1. The conjecture posits that no matter the starting number, the sequence will eventually reach the value 1.

# importing the required module
import matplotlib.pyplot as plt

# declare x-axis
iteration_num_list = []
x = 0
iteration_num_list.append(x)

# check for positive number
positive = False
while positive == False:
    print("Enter any number: ")
    num = float(input())

    if num <= 0:
        print("INVALID, ENTER POSITIVE NUMBER: ")
        continue
    else:
        break


# declare y-axis
num_list = []
num_list.append(num)

num = 3 * num + 1

while num > 1:
    # if num is even, then divide by 2
    if num % 2 == 0:
        print(num)
        num = num / 2
        x = x + 1
        iteration_num_list.append(x)
        num_list.append(num)
        continue
    # if num is odd, repeat 3(num)+1
    else:
        print(num)
        num = 3 * num + 1
        x = x + 1
        iteration_num_list.append(x)
        num_list.append(num)
        continue

print(num)
print("Done!")

# plotting the points
plt.plot(iteration_num_list, num_list)
plt.xlabel('iteration')
plt.ylabel('x in 3(x) + 1')
plt.title('3(x) + 1')
plt.show()