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

15 views (last 30 days)
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 Comments
Stephen23
Stephen23 on 23 Sep 2017
Edited: Stephen23 on 23 Sep 2017
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.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 23 Sep 2017
Edited: Stephen23 on 23 Sep 2017
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

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!