In: Computer Science
PYTHON PROGRAM!
Exercise 1 - The Collatz Conjecture
The Collatz conjecture was a mathematical proposal set forward by Lothar Collatz in 1937, also known as the 3n + 1 conjecture.
The conjecture is summarized as follows:
For example, if you start with 12, the series would be 12, 6, 3, 10, 5, 16, 8, 4, 2, 1, and takes 9 iterations to get to 1.
The Collatz conjecture says that any starting number will eventually end up at 1. However, it is still unproven (see Mathematician Proves Huge Result on ‘Dangerous’ Problem (Links to an external site.) for some recent progress!).
Collatz visualization |
Write a python program that will determine how many iterations it takes for each starting value from 1 to 100 (experiment with higher values if you want!). Write out the starting value and number of iterations to a comma delimited csv file (i.e. one set of comma separated values per line). Also plot the result (starting value vs. iterations) with a visible marker for the points (you can choose which ever style you like) and no line. Make sure to give your plot a title and label the axes appropriately.
Code: Logic to find number of iterations for starting value ranging from 1 to 100
l_val = []
l_itr = []
for i in range(1,101):
val = i
itr = 0
while val != 1:
itr += 1
if val%2 == 0:
val = val/2
else:
val = 3*val + 1
l_val.append(i)
l_itr.append(itr)
print("For starting value =", l_val[11], ", No. of iterations =", l_itr[11])
Code to save CSV file:
import csv
with open('sample.csv', 'w') as fp:
writer = csv.writer(fp)
writer.writerows(zip(l_val, l_itr))
Code to plot:
import matplotlib.pyplot as plt
plt.plot(l_val,l_itr,'-or')
plt.title('Collatz conjecture', fontsize=18)
plt.xlabel('Starting Value', fontsize=16)
plt.ylabel('Number of Iterations', fontsize=16)
Plot:
PS: Let me know if anyone face any issue or have some doubts.