Java Program to Find LCM of Two Numbers

1. Introduction

The Least Common Multiple (LCM) of two numbers is the smallest number that is a multiple of both. Finding the LCM is a common problem in mathematics and computer science, often solved using the Greatest Common Divisor (GCD) as part of the solution. This blog post will show how to calculate the LCM of two numbers in Java, demonstrating basic arithmetic operations, loops, and the use of the Euclidean algorithm for finding the GCD.

2. Program Steps

1. Define a method to find the GCD of two numbers using the Euclidean algorithm.

2. Define a method to calculate the LCM of two numbers using the GCD found in step 1.

3. Read two numbers from the user.

4. Call the LCM method with the two numbers and display the result.

5. Close any resources used for input.

3. Code Program

import java.util.Scanner;

public class FindLCM {
    public static void main(String[] args) {
        // Scanner for reading user input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the first number:");
        int firstNumber = scanner.nextInt();
        System.out.println("Enter the second number:");
        int secondNumber = scanner.nextInt();

        // Calculate LCM
        int lcm = lcm(firstNumber, secondNumber);

        // Display LCM
        System.out.println("The LCM of " + firstNumber + " and " + secondNumber + " is: " + lcm);

        scanner.close(); // Close scanner
    }

    // Method to find GCD using the Euclidean algorithm
    private static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        } else {
            return gcd(b, a % b);
        }
    }

    // Method to calculate LCM using the formula: lcm(a, b) = (a * b) / gcd(a, b)
    private static int lcm(int a, int b) {
        return (a * b) / gcd(a, b);
    }
}

Output:

Enter the first number:
15
Enter the second number:
20
The LCM of 15 and 20 is: 60

Explanation:

1. The program starts by importing the Scanner class, which is used to read input from the user. The user is asked to enter two numbers, which are stored in firstNumber and secondNumber.

2. The gcd method implements the Euclidean algorithm to find the greatest common divisor of the two numbers. This method recursively calls itself, reducing the problem size at each step until the base case (when the second number becomes 0) is reached.

3. The lcm method calculates the least common multiple of the two numbers using the formula lcm(a, b) = (a * b) / gcd(a, b). This formula relies on the GCD to find the LCM.

4. After calculating the LCM, the program prints the result to the console.

5. Finally, the Scanner object is closed to prevent resource leaks, adhering to best practices in resource management.

Comments