Clear Filters
Clear Filters

Executing two loops at the same time

1 view (last 30 days)
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?

Accepted Answer

JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH on 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 Comment
Sang Heon Lee
Sang Heon Lee on 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??

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!