Calculate LCM using GCD
Java Programming Language Decision Making and Looping in java (Article) Decision Making and Looping in java (Program)
25Program:
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); } }
Output:
The LCM of 72 and 120 is 360.
Explanation:
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:
- Two integers
n1
andn2
are initialized with values 72 and 120 respectively. - Another integer
gcd
is initialized to 1, which will hold the greatest common divisor ofn1
andn2
.
- Two integers
-
Finding the Greatest Common Divisor (GCD):
- A
for
loop is used to iterate from 1 to the smaller ofn1
andn2
. - Inside the loop, it checks if the current value of
i
is a factor of bothn1
andn2
. If it is, then it updates the value ofgcd
toi
. - After the loop,
gcd
will hold the greatest common divisor ofn1
andn2
.
- A
-
Calculating the Least Common Multiple (LCM):
- LCM can be calculated using the formula:
LCM = (n1 * n2) / GCD
. - Using this formula, it calculates the LCM and stores it in the variable
lcm
.
- LCM can be calculated using the formula:
-
Output:
- Finally, it prints the calculated LCM using the
printf
method.
- Finally, it prints the calculated LCM using the
-
Output:
- The program prints out the calculated LCM of
n1
andn2
using theprintf
method.
- The program prints out the calculated LCM of
In summary, this program calculates the LCM of two given numbers (n1
and n2
) using the GCD method and then prints the result.
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.