Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Consider the following algorithm: Start with a positive integer. If the number is even, divide it by two; otherwise triple it and add one.
Consider the following algorithm: Start with a positive integer. If the number is even, divide it by two; otherwise triple it and add one. Repeat the process until the number 1 is obtained. The Collatz conjecture states that the above algorithm will reach 1 eventually for any starting value. Remarkably, for a problem that can be described so simply, it is an unsolved problem in mathematics as to whether the conjecture is true and its proof has been described as "completely out of reach of present day mathematics". Complete the below function collatz that applies the above algorithm for a given postive integer n and returns the number of steps required to reach a value of 1. If the number of steps reaches the value of max_steps (without the algorithm reaching 1) then NaN is returned. Your code must use a for loop and at least one if statement. Examples: (i) The following code steps = collatz (6,100) should return: steps = 8 since it takes 8 steps starting with a value of 6 to reach 1 (values generated along the way are: 3, 10, 5, 16, 8, 4, 2, 1). (ii) The following code steps = collatz (6,4) should return: steps = NaN since after 4 steps the algorithm has not reached 1 when starting with a value of 6.
Step by Step Solution
★★★★★
3.45 Rating (155 Votes )
There are 3 Steps involved in it
Step: 1
Step 12 Answer Lets solve this question in the MATLAB programming language The logic of the program ...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started