Algorithm
- Input the two numbers (num1, num2) for which you want to find the LCM.
- Find the maximum of the two numbers and assign it to a variable max.
- Initialize a variable lcm with the value of max, as the LCM cannot be smaller than the larger number.
- Use a loop to check if the lcm is divisible by both num1 and num2.
- If divisible, exit the loop as you have found the LCM.
- If not divisible, increment lcm by max in each iteration.
- Output the value of lcm as the LCM of num1 and num2.
Code Examples
#1 Code Example- LCM using while Loop and if Statement
Code -
Java Programming
public class Main {
public static void main(String[] args) {
int n1 = 72, n2 = 120, lcm;
// maximum number between n1 and n2 is stored in lcm
lcm = (n1 > n2) ? n1 : n2;
// 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;
}
}
}
Copy The Code &
Try With Live Editor
Output
The LCM of 72 and 120 is 360.
#2 Code Example- Calculate LCM using GCD
Code -
Java Programming
public class Main {
public static void main(String[] args) {
int n1 = 72, n2 = 120, gcd = 1;
for(int i = 1; i < = n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if(n1 % i == 0 && n2 % i == 0)
gcd = i;
}
int lcm = (n1 * n2) / gcd;
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
}
}
Copy The Code &
Try With Live Editor
Demonstration
Java Programing Example to Find LCM of two Numbers-DevsEnv