Executing two loops at the same time

1 vue (au cours des 30 derniers jours)
Sang Heon Lee
Sang Heon Lee le 21 Sep 2017
Commenté : Sang Heon Lee le 21 Sep 2017
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?

Réponse acceptée

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH le 21 Sep 2017
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 commentaire
Sang Heon Lee
Sang Heon Lee le 21 Sep 2017
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??

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by