Java program to find lcm of two numbers

To find the LCM (Least Common Multiple) of two numbers in Java, you can use the following formula:

re‮ot ref‬:theitroad.com
LCM = (number1 * number2) / GCD(number1, number2)

Here, number1 and number2 are the two numbers for which you want to find the LCM, and GCD is the Greatest Common Divisor of the two numbers.

To find the GCD of two numbers, you can use the Euclidean algorithm. Here's an example program that demonstrates how to find the LCM of two numbers in Java:

public class LCM {
    public static void main(String[] args) {
        int num1 = 12;
        int num2 = 18;

        int gcd = findGCD(num1, num2);
        int lcm = (num1 * num2) / gcd;

        System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
    }

    public static int findGCD(int num1, int num2) {
        if (num2 == 0) {
            return num1;
        }

        return findGCD(num2, num1 % num2);
    }
}

In this program, we define two integer variables num1 and num2 and initialize them with some values. We then call the findGCD method to find the GCD of the two numbers, and use the formula to calculate the LCM.

The findGCD method uses the Euclidean algorithm to find the GCD of two numbers. If the second number is 0, we return the first number. Otherwise, we call the findGCD method recursively with the second number and the remainder of the first number divided by the second number.

After finding the LCM, we print it out to the console using the System.out.println method.

When you run the program, the output will be:

LCM of 12 and 18 is: 36

As you can see, the program successfully finds the LCM of two numbers and prints it to the console.