I need help determining and displaying the number of steps it takes to complete this loop when any integer is entered.

11 次查看(过去 30 天)
so I have figured out how to write the while loop I need. It looks like this:
b=0;
b=input('Enter an integer greater than 1:');
while b>1
if mod (b,2)==0;
b=b/2;
else mod(b,2)~=0;
b=(b*3)+1;
end
end
It takes any given integer, multiplies it by 3 then adds 1 if it is odd. It divides the number by 2 when it is even. I need to represent the number of steps it takes this loop to get to the number 1, which is where it ends. I've tried "b=length(b)' and it just says b=1. I cannot figure out how to write a code to display how many steps it takes to reach 1 when an integer is given. Example, if the user enters "3" the steps would be 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1 If the user were to enter this particular integer, I would need my output to be "s=7."
  2 个评论
Stephen23
Stephen23 2017-9-23
编辑:Stephen23 2017-9-23
Note that you do not need both of these conditions:
if mod (b,2)==0;
...
else mod(b,2)~=0;
...
end
If mod(b,2)==0 then the first case will run. Clearly all remaining cases must be not equal to zero, so all you need is:
if mod(b,2)==0
...
else
...
end
I also removed the semi-colons, which are not required after if or switch conditions: the semi-colon can be used to suppress results of an operation, but conditions are never displayed.

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2017-9-23
编辑:Stephen23 2017-9-23
You just need to add a counter variable, here I used cnt:
str = input('Enter an integer greater than 1: ','s');
num = str2double(str); % safer for INPUT to return a string!
cnt = 0;
while num>1
cnt = cnt+1;
if mod(num,2)
num = num*3+1;
else
num = num/2;
end
end
disp(cnt)
And tested:
>> temp0 % or whatever the name of your script is.
Enter an integer greater than 1: 3
7

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by