Visualizing Collatz conjecture with Python

Collatz conjecture aka 3n+1 problem is notoriously famous for being the simplest to explain and yet unsolved problem in mathematics.

The problem goes like this: take any positive integer number; if it’s even – double the number, if it’s odd –triple it and add 1. Keep doing this to the new number you get until you finally reach 1. The conjecture is that after all these iterations, you always reach 1, no matter which positive integer you started from.

While no one has proved the conjecture, it has been verified for every number less than 268, which is more than 295 quintillion or 295 billion billion.

Here we are going to simulate this problem using Python. I’m using VS Code but you can prefer to use any IDE.

import matplotlib.pyplot as plt

num = int(input("Enter a positive integer: "))
seqList = [num]

while (num > 1):
    if num % 2 == 0:
        num = num/2
    else:
        num = 3 * num + 1
    seqList.append(num)   

print("Number of steps: ", len(seqList)-1)
print("Max step value: ", max(seqList))
print(seqList)

# Plotting graph
x = list(range(0,len(seqList)))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,max(seqList)+5)

# x and y axis
plt.plot(x, seqList)

# Annotating graph
for i,j in zip(x, seqList):
    ax.annotate(str(j), xy=(i+0.1,j+0.5))

plt.xlabel("Number of steps")
plt.ylabel("Value")
plt.grid()
plt.show()
Number 27 unexpectedly hops up and down 111 times reaching a maximum higher than the elevation of Mt. Everest in meters. Interestingly, 27 is the only positive integer that is 3 times the sum of its digits.
Plot for number 15