Why is this loop not ending?

3 ビュー (過去 30 日間)
Simone Frauenfelder
Simone Frauenfelder 2017 年 4 月 26 日
コメント済み: Rena Berman 2017 年 4 月 28 日
function [ number ] = SmallestNumber(n,a,b)
% Smallest natural number function
% inputs:
% n = maximum value
% a = first number n should be divisible
% b = second number n should be divisible by
% output:
% number = the smallest number (not exceeding the value of 'n') that is % divisible by 'a' and 'b'
i = 1;
while i =< n
A = rem(i,a);
B = rem(i,b);
if A <= 0 && B <= 0;
number = i
else
i = i + 1;
end
end
This loop is an infinite loop, how can I fix it so it ends and displays 'number = '?
Thank you!
  2 件のコメント
Stephen23
Stephen23 2017 年 4 月 26 日
@Simone Frauenfelder: editing your question text away will not encourage people to help you. You unilaterally decide that our volunteer efforts are disposable according to your own wishes, because now our answers are meaningless to anyone else. This will not encourage people to help you, if they know that they will be treated as your own personal consultancy.
Rena Berman
Rena Berman 2017 年 4 月 28 日
(Answers Dev) Restored edit

サインインしてコメントする。

回答 (2 件)

KL
KL 2017 年 4 月 26 日
編集済み: KL 2017 年 4 月 26 日
Your loop variable increment i=i+1; is part of the else case so once the condition becomes true, i is not incremented. Move that statement outside and you'll see your result. Something like this
if A <= 0 && B <= 0;
number = i
break;
end
i = i + 1;
end % end from while loop
Adding break after finding the number breaks the loop.

Stephen23
Stephen23 2017 年 4 月 26 日
編集済み: Stephen23 2017 年 4 月 26 日
It would be simpler to use a for loop, then break is not required:
function num = SmallestNumber(n,a,b)
num = Inf;
for k = n:-1:2
if rem(k,a)==0 && rem(k,b)==0
num = k;
end
end
end
And tested:
>> SmallestNumber(100,9,6)
ans = 18

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by