# LCM Loops

Optional Node

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.

Alternatively, you can try out Learneroo before signing up.

• #### zkvarz

Three 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

@zkvarz, you can now view more cases.

• #### zkvarz

Thank you for cases, admin! I think this way:
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

so we divide 10 by 5. I still can't get it, why not 2

• #### zkvarz

Admin, I thought I get this task but still, "other output" is wrong. Something I do the wrong way.

• #### David

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 ){

• #### Learneroo

@David, `i` will keep increasing until `a*i` is a product of `b`. So it will stop when i=5 and a=3 and return that product.

• #### 許友誠

import java.util.Scanner;

public class Main {

``````static int doStuff(int a, int b)
{

int max=1;
for(int i=2;i<=a;i++)
{
if(a%i==0 && b%i==0)
``````
• #### kevintaw

A little difficult

• #### Jig

This worked for me but I don't understand it, anyone please explain

``````    int multiple =0;
for(int i=1; i<=100; i++){
multiple=a*i;

if (multiple%b ==0 && multiple%a==0){
return multiple;

}
}
return multiple;
``````
• #### Bernard Mitchell

``````int c=0;
while(c%b!=0){
c=c+a;
}
return c;
``````

I don't understand why my code isn't working.

• #### Learneroo

If `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

Is this a smart solution. I mean it does makes a different if a<b or b<a right?

my code

• #### arya

int LCM = 1;
while (!(((LCM % a) == 0) && ((LCM % b) == 0))){
LCM++;
}
return LCM;

• #### avisuisse

in R
leastcm = function(a, b) {

status = F

while(status == F) {

``````for (i in a:(a*b)) {

if (i %% a == 0 & i %% b == 0) {
status = T
print(i)
break
}
}
``````

}
}

• #### avisuisse

leastcm = function(a, b) {

status = F

while(status == F) {

``````for (i in a:(a*b)) {

if (i %% a == 0 & i %% b == 0) {
status = T
print(i)
break
}
}
``````

}
}