Azzera filtri
Azzera filtri

Executing two loops at the same time

1 visualizzazione (ultimi 30 giorni)
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?

Risposta accettata

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH il 21 Set 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 Commento
Sang Heon Lee
Sang Heon Lee il 21 Set 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??

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by