Calculate LCM using GCD
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);
}
}
The LCM of 72 and 120 is 360.
This Java program calculates the Least Common Multiple (LCM) of two numbers using the GCD (Greatest Common Divisor) method.
Here's a breakdown of how the code works:
Initialization:
n1 and n2 are initialized with values 72 and 120 respectively.gcd is initialized to 1, which will hold the greatest common divisor of n1 and n2.Finding the Greatest Common Divisor (GCD):
for loop is used to iterate from 1 to the smaller of n1 and n2.i is a factor of both n1 and n2. If it is, then it updates the value of gcd to i.gcd will hold the greatest common divisor of n1 and n2.Calculating the Least Common Multiple (LCM):
LCM = (n1 * n2) / GCD.lcm.Output:
printf method.Output:
n1 and n2 using the printf method.In summary, this program calculates the LCM of two given numbers (n1 and n2) using the GCD method and then prints the result.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.