Skip to content

Instantly share code, notes, and snippets.

@dougmcnally
Last active March 6, 2024 19:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dougmcnally/cbe15f010415130e20bfeff4f6f526a0 to your computer and use it in GitHub Desktop.
Save dougmcnally/cbe15f010415130e20bfeff4f6f526a0 to your computer and use it in GitHub Desktop.
Python code for plotting the number of interations required to reach "1" with the Collatz conjecture iteration process.
# Collatz Conjecture
import matplotlib.pyplot as plt
MAX = 1000000
n_list = range(1,MAX+1)
steps = list()
for n in n_list:
count = 0
while not n == 1:
if n % 2 == 0:
n /= 2
else:
n = 3*n + 1
count += 1
steps.append(count)
plt.xlabel("$n$",fontsize=18)
plt.ylabel("Steps to reach 1")
plt.title("Collatz Conjecture")
plt.plot(n_list,steps,'o',color="blue", ms=.5, mec="red",mew=0.0)
plt.xlim(xmax=MAX)
plt.ylim(ymin=0)
plt.savefig("collatz_"+str(MAX)+".png",bbox_inches="tight",dpi=600)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment