필터 지우기
필터 지우기

how can I use a while loop for LCM?

조회 수: 1 (최근 30일)
Lorayne Reyes
Lorayne Reyes 2018년 6월 12일
답변: Matt Dickson 2018년 6월 12일
I want to write a program that will allow me to add the value of 'x', and then if the sum is equal to the input for y stop and display that value as the LCM. But, if not, add y+y+y+y.... until x=y.
  댓글 수: 1
Paridhi Yadav
Paridhi Yadav 2018년 6월 12일
Can you explain clearly what you want ?

댓글을 달려면 로그인하십시오.

답변 (1개)

Matt Dickson
Matt Dickson 2018년 6월 12일
To do it iteratively as you laid out, you'd have something like
function [leastCommon] = lcm(a,b)
a1 = a;
b2 = b;
while a1 ~= b1
if a1 > b1
b1 = b1 + b;
else
a1 = a1 + a;
end
end
leastCommon = a1;
end
I'm not sure if you're set on doing it the way you described, but a simpler way to find the LCM is to use the greatest common division (GCD). Say you want to know the LCM of two numbers, a and b. Then
LCM = (a * b) / gcd(a,b)
The GCD is easy to find via the Euclidean algorithm, which is recursively defined as
function [ret] = gcd(a, b)
if b == 0
ret = a;
else
ret = gcd(b, mod(a, b));
end

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by