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

조회 수: 13 (최근 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.
Walter Roberson
Walter Roberson 2017년 9월 24일
My system is busy at the moment, but I wonder what mod(inf,2) is ? Potentially it is neither 0 nor 1.

댓글을 달려면 로그인하십시오.

채택된 답변

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