LCM

The least / lowest common multiple (LCM) of two or more than two numbers is the smallest number (not zero) which is a multiple of all of the numbers.

Logic

Let declare one temporary variable lcm by 1, we are going to use this variable to store LCM.

Here we are calculating LCM of two user given numbers, after taking both the numbers (num1, num2) from the user, we have to find out the maximum number, we store the maximum one in variable max and also assign the value of max to the variable i.

Now we start one infinite loop while(1), inside the loop we have to check if both the numbers can completely divide max value. If yes then we terminate the loop with break statement and assign current value of “i” to lcm, otherwise, continue the loop.

Once the loop is over, simply print the variable lcm containing the lowest common multiple of num1 and num2.

Program

import java.util.Scanner;

public class FindLCM {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Take two numbers from user
        System.out.print("Enter any two number : ");
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();

        // Find the max number
        int max = (num1 > num2) ? num1 : num2;

        int i = max;
        int lcm = 1;

        while(true) {

            if((i % num1) == 0 && (i % num2) == 0) {
                lcm = i;
                break;
            }

            i += max;
        }

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

}

Output

Enter any two number : 6 24
LCM of 6 and 24 : 24