How can I solve this odd/even loop question (hailstone sequence)?
Mostrar comentarios más antiguos
n = 71
If n is even, divide it by 2 to get n / 2.
If n is odd, multiply it by 3 and add 1 to obtain 3n + 1.
Repeat process until n = 1.
I need to find out how many steps it takes to reach 1..
thanks!
2 comentarios
Thorsten
el 22 de Sept. de 2015
What have you tried so far? Where did you got stuck?
mrs_matlab_rookie_thanks
el 22 de Sept. de 2015
Respuesta aceptada
Más respuestas (1)
Thorsten
el 22 de Sept. de 2015
First you can skip the 1, and just write n(ii).
Next you have forgotten to assign the new value, and you have to move the increment of ii outside the else-clause
if mod(n(ii),2)==1
n(ii+1) = 3*n(ii)+1;
else
n(ii+1) = n(ii)/2;
end
ii=ii+1;
Finally you have to change the while loop condition; while n(ii) == 1 means that the loops only continues if the n is 1, but it should continue if n is NOT 1.
1 comentario
mrs_matlab_rookie_thanks
el 22 de Sept. de 2015
Categorías
Más información sobre Resizing and Reshaping Matrices en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!