LCM Loops
Optional Node
Collapse Content
Show Content
In this challenge, see if you can use your knowledge of loops, the %
operator and some math to come up with an algorithm to solve an important math problem.
Challenge
Given two numbers a
and b
can you return their Least Common Multiple (LCM)? A LCM of a
and b
is the smallest number that is a multiple of both a
and b
.
(Remember you can use %
to check if a number divides evenly into another number.)
Challenge
Given two numbers a
and b
return their LCM.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
zkvarz
Jan 17, 6:06 AMThree examples above shows correct, but "other output" is wrong. Maybe I misunderstood the task, maybe it's better to show more examples in I/O.
Learneroo
Jan 17, 9:39 AM@zkvarz, you can now view more cases.
zkvarz
Jan 18, 9:59 AMThank you for cases, admin! I think this way:
5 10, answer is 10.
In this case we can't divide 5 evenly so we divide 10 until we get smallest even number 2, therefore 5*2 = 10.
zkvarz
Jan 18, 10:47 AMso we divide 10 by 5. I still can't get it, why not 2
zkvarz
Jan 18, 11:12 AMAdmin, I thought I get this task but still, "other output" is wrong. Something I do the wrong way.
David
Mar 17, 8:27 PMDear Admin,
On the Explanation:
"Explanation: You could use a while loop, or a compact for loop:
int i;
for(i=1; a*i % b != 0; i = i +1 ){
}
return a*i; "
Why would you return a*i instead of just i. My noobness probably doesn't see the logic but in the first example wouldn't you be returning 3*15 which equals 45 instead of just i which is 15?
Best Regards,
Thanks.
Learneroo
Mar 17, 9:13 PM@David,
i
will keep increasing untila*i
is a product ofb
. So it will stop when i=5 and a=3 and return that product.許友誠
May 16, 2:05 AMimport java.util.Scanner;
public class Main {
}
kevintaw
Jun 12, 11:38 AMA little difficult
Jig
Jun 21, 7:33 PMThis worked for me but I don't understand it, anyone please explain
Bernard Mitchell
Jul 6, 4:01 PMI don't understand why my code isn't working.
Learneroo
Jul 6, 4:19 PMIf
c
is 0 , what happens when you reach the while condition? (You should always test out smaller parts of your code to know what's going on.)thales
Jul 16, 1:33 PMIs this a smart solution. I mean it does makes a different if a<b or b<a right?
my code
arya
Feb 12, 1:32 PMint LCM = 1;
while (!(((LCM % a) == 0) && ((LCM % b) == 0))){
LCM++;
}
return LCM;
avisuisse
Oct 3, 10:29 PMin R
leastcm = function(a, b) {
status = F
while(status == F) {
}
}
avisuisse
Oct 3, 10:29 PMleastcm = function(a, b) {
status = F
while(status == F) {
}
}