If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To calculate the Least Common Multiple (LCM) of two numbers in Java, you can use the formula:
LCM(a, b) = (|a * b|) / GCD(a, b)
where GCD(a, b) represents the Greatest Common Divisor of the two numbers a and b. Since we have already discussed how to calculate GCD in the previous answer, you can use the same calculateGCD
method from the previous example. Here's a Java program to calculate the LCM of two given numbers:
javaCopy code
import java.util.Scanner;
public class LCDCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
// Calculate the LCM using the formula LCM(a, b) = (|a * b|) / GCD(a, b)
int lcm = calculateLCM(num1, num2);
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
scanner.close();
}
// Function to calculate LCM using GCD
public static int calculateLCM(int a, int b) {
int gcd = calculateGCD(a, b);
return Math.abs(a * b) / gcd;
}
// Function to calculate GCD using the Euclidean algorithm
public static int calculateGCD(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}
Example output:
mathematicaCopy code
Enter the first number: 12
Enter the second number: 18
LCM of 12 and 18 is: 36
In the program above, we take the user input for the two numbers and store them in num1
and num2
variables. We then call the calculateLCM
function to calculate the LCM using the GCD method we defined earlier. The calculateLCM
function uses the formula to compute the LCM and returns the result.
The program then prints the LCM of the two numbers to the console.
Comments: 0