4. (14) The routine \"3N+1* follows these rules: If a given N is odd, multiply i
ID: 3748778 • Letter: 4
Question
4. (14) The routine "3N+1* follows these rules: If a given N is odd, multiply it by 3 and add 1. If the given N is even, divide it by 2. Repeat this rule on the new value until you get 1, if ever. For example, start with the number 3: because 3 is odd, we multiply by 3 and add 1 giving us 10. 10 is even so we divide it by 2, giving us 5. 5 is odd so we multiply by 3 and add one, giving us 8. We divide 8 (even) by two giving 4. We divide 4 (even) by two giving 2. We divide 2 (even) by 2 to give us 1. Once we have one, we stop. This example took six iterations to get to one. Every value of N that anyone has ever checked eventually leads to 1, but it is an open mathematical problem (known as the Collatz conjecture) whether every value of N eventually leads to 1 Run your program repeatedly for initial integer N values from 2 to 100. Hint: Use a A. Plot the number of steps taken to get to 1 against the starting value of N B. Plot the maximum value before getting to 1 against the starting value of N C. Plot the maximum value versus the number of steps (include proper labels). for loop around your function in HW3A. (include proper labels). Use a log-log scale. (include proper labels). Use a log-log scale. Use a log-log scale. Is there a general trend between the two values?Explanation / Answer
import matplotlib.pyplot as plt
n_list = range(1,101)
steps = list()
max_vals = list()
for n in n_list:
count = 0
max_val = 0
while not n == 1:
if n % 2 == 0:
n /= 2
else:
n = 3*n + 1
count += 1
max_val = max(max_val, n)
steps.append(count)
max_vals.append(max_val)
#a
plt.xlabel("$n$",fontsize=10)
plt.ylabel("Steps to reach 1")
plt.title("Collatz Conjecture")
plt.plot(n_list,steps,linewidth=1.0)
plt.xlim(xmax=101)
plt.yscale('log')
plt.show()
#b
plt.xlabel("$n$",fontsize=10)
plt.ylabel("Maximum Value Before Reaching 1")
plt.title("Collatz Conjecture")
plt.plot(n_list,max_vals,linewidth=1.0)
plt.xlim(xmax=101)
plt.yscale('log')
plt.show()
#c. Yes, both the values are increase till a point and then increment in maximum value becomes #constant as compared to increase in steps required.
plt.xlabel("Steps Needed to Reach 1")
plt.ylabel("Maximum Value Before Reaching 1")
plt.title("Collatz Conjecture")
plt.plot(steps,max_vals,'ro')
plt.yscale('log')
plt.xscale('log')
plt.show()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.