How would my script to show this in the command window?
10 views (last 30 days)
Show older comments
michael story
on 25 Sep 2018
Edited: michael story
on 26 Sep 2018
My function is [s,m]=collatz(X). If I want s to equal the number of steps it takes for the number to equal one then how would I set it up? I know the idea is that the number of steps (s) increases by one every time the number goes through the while-loop. Then I need m to equal the maxvalue which comes from the biggest value in the list. Ex: >>[s,m]=collatz(3) s=7 m=16 since the list is 3-10-5-16-8-4-2-1
function[s,m]=collatz(x)
%This function will show the steps and maxvalue of even and odd natural
%numbers.It will show the show the number of steps it can repeat as long as
%the number is greater than one. It will show the maxvalue in the list
%Even numbers will be divided by 2
%Odd numbers will be multiplied by 3 and add to by one
%both will run as long as the result is greater than 1
clc
s=
m=
while x>1
if mod(x,2)==0 %shows x(natural number is even)
x=x/2
elseif mod(x,2)==1 %shows x(natural number is odd)
x=x*3+1
end
end
0 Comments
Accepted Answer
Fangjun Jiang
on 25 Sep 2018
Michael,
Initially, set s to be zero because no loop has been executed yet. Set m to be the same as x.
Inside the loop, s is increased by 1 after every iteration of the while-loop, like s=s+1. Set m to be equal to x if x is greater than m.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!