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

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

MATLABwhile loop

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.”

Best Answer

  • 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
  • Add a Comment

    Your email address will not be published. Required fields are marked *