Java Program To Find LCM of Two Numbers
Java Program To Find LCM of Two Numbers
// Always true
while(true) {
if( lcm % n1 == 0 && lcm % n2 == 0 ) {
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
break;
}
++lcm;
}
}
}
Output
In this program, the two numbers whose LCM is to be found are stored in variables n1
and n2 respectively.
Then, we initially set lcm to the largest of the two numbers. This is because, LCM cannot
be less than the largest number.
Inside the infinite while loop ( while(true) ), we check if lcm perfectly divides both n1
and n2 or not.
If it does, we've found the LCM. We print the LCM and break out from the while loop using
break statement.
If you don't know how to calculate GCD in Java, check Java Program to find GCD of two
numbers.
Here, inside the for loop, we calculate the GCD of the two numbers - n1 and n2 . After
the calculation, we use the above formula to calculate the LCM.