Java Program to Find LCM of Two Numbers
The LCM (Least Common Multiple) of two numbers is the smallest number that is divisible by both numbers.
In this tutorial, we will create a Java program to find the LCM of two numbers using a mathematical approach.
By the end of this guide, you will understand how LCM and GCD are related.
Concept Overview
The LCM of two numbers can be calculated using the formula:
LCM(a, b) = (a × b) / GCD(a, b)
This method is efficient and avoids checking multiple numbers.
Program
import java.util.Scanner;
public class LCMOfNumbers {
static int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = sc.nextInt();
System.out.print("Enter second number: ");
int b = sc.nextInt();
int lcm = (a * b) / gcd(a, b);
System.out.println("LCM is: " + lcm);
}
}
Output
Enter first number: 12
Enter second number: 15
LCM is: 60
Detailed Explanation
The program first defines a function to calculate GCD using the Euclidean algorithm.
It then takes two numbers as input from the user.
Using the formula LCM = (a × b) / GCD, the program calculates the LCM.
Finally, the result is displayed.
Example Walkthrough
Let us consider 12 and 15.
GCD(12, 15) = 3.
LCM = (12 × 15) / 3 = 60.
Applications
LCM is used in scheduling problems, fractions addition, and synchronization tasks.
Advantages of This Approach
This method is efficient and avoids unnecessary iterations.
It demonstrates the relationship between LCM and GCD.
Limitations
The multiplication (a × b) may cause overflow for very large numbers.
Improvements You Can Make
You can use long data type to handle larger numbers.
You can also implement an iterative LCM approach without using GCD.
This Java program strengthens understanding of mathematical relationships and efficient coding techniques.
Codecrown