Executing two loops at the same time

1 次查看(过去 30 天)
What I am trying to do is applying different calculations depending on whether the number is odd or even.
n = input('Your number = ');
i = 1;
while n ~= 1
while rem(n,2) == 0
n = (n/2);
i = i + 1;
end
while rem(n,2) == 1
n = (3*n) + 1;
i = i + 1;
end
end
i
This is what I have currently. However when I enter n, the script runs forever and I have to restart the matlab. How can I make this loop to continue until n reaches 1?

采纳的回答

JESUS DAVID ARIZA ROYETH
you can do like this:
n = input('Your number = ');
i = 1;
while n ~= 1
while rem(n,2) == 0 && n ~= 1
n = (n/2);
i = i + 1;
end
while rem(n,2) == 1 && n ~= 1
n = (3*n) + 1;
i = i + 1;
end
end
i
  1 个评论
Sang Heon Lee
Sang Heon Lee 2017-9-21
Thank! It works!!!
but I still cannot understand how the script you provided works and mine doesn't...
does && n ~= 1 matter..? I mean, n ~= 1 is already given from the first while, and what does n ~= 1 behind the subsequent while do??

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by