I need help determining and displaying the number of steps it takes to complete this loop when any integer is entered.
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Kevin Smith
el 23 de Sept. de 2017
Comentada: Walter Roberson
el 24 de Sept. de 2017
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 comentarios
Stephen23
el 23 de Sept. de 2017
Editada: Stephen23
el 23 de Sept. de 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.
Walter Roberson
el 24 de Sept. de 2017
My system is busy at the moment, but I wonder what mod(inf,2) is ? Potentially it is neither 0 nor 1.
Respuesta aceptada
Stephen23
el 23 de Sept. de 2017
Editada: Stephen23
el 23 de Sept. de 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
Más respuestas (0)
Ver también
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!