Write Java program to Find the (LCM) Lowest Common Multiple


This Java program finds the Lowest Common Multiple (LCM) of two numbers entered by the user. The program uses the Euclidean algorithm to find the Greatest Common Divisor (GCD) of the two numbers, and then uses the formula LCM = (num1 * num2) / GCD to find the LCM.

The program starts by creating a Scanner object to read input from the user. It then declares several variables to store the user's input, the remainder of dividing the larger number by the smaller number, the LCM, and two temporary variables to help swap the values of num1 and num2 if necessary.

The program then prompts the user to enter two integers, which are stored in the variables num1 and num2. The program then checks which of the two numbers is larger, and swaps their values if necessary so that x (the larger number) is assigned to num1, and y (the smaller number) is assigned to num2.

Next, the program uses a while loop to find the GCD of num1 and num2. The loop repeatedly calculates the remainder of dividing x by y, and updates the values of x and y accordingly. The loop continues until rem (the remainder) is 0, indicating that y is the GCD of num1 and num2.

Finally, the program calculates the LCM using the formula LCM = (num1 * num2) / GCD, and stores the result in the variable lcm. The program then prints out the value of lcm using System.out.printf.

Source Code

import java.util.Scanner;
public class Find_LCM
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		int num1 = 0,num2 = 0;
		int rem = 0,lcm = 0, x = 0, y = 0;
 
		System.out.printf("Enter the Number 1 : ");
		num1 = input.nextInt();
		System.out.printf("Enter the Number 2 : ");
		num2 = input.nextInt();
 
		if (num1 > num2)
		{
			x = num1;
			y = num2;
		}
		else
		{
			x = num2;
			y = num1;
		}
		rem = x % y;
		while (rem != 0)
		{
			x = y;
			y = rem;
			rem = x % y;
		}
		lcm = num1 * num2 / y;
		System.out.printf("Lowest Common Multiple is : "+lcm);
	}
}

Output

Enter the Number 1 : 67
Enter the Number 2 : 78
Lowest Common Multiple is : 5226

Example Programs