Write a script that asks for an integer (n) and then computes the following based on the value of the integer...
Show older comments
2) Write a script that asks for an integer (n) and then computes the following based on the value of the integer:
While the value of n is greater than 1, replace the integer with half of its value (n/2) if the integer is even. Otherwise, replace the integer with three times its value, plus 1 (3*n + 1).
Make a provision to count the number of values in (or the length of) the sequence that results.
Example calculation: If n = 10, the sequence of integers is 5, 16, 8, 4, 2, 1 and so the length is 6.
Make a plot of the length of the sequence that occurs as a function of the integers from 2 to 30. For example, when n = 10, the length is 6 while for n = 15, the length is 17.
Is there any pattern? Try larger numbers to see if any pattern occurs. Is there any integer for which the sequence does not terminate?
Answers (0)
Categories
Find more on Argument Definitions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!