Java Program To find HCF And LCM

Least Common Multiple(LCM)

LCM is also called Least Common Divisor (LCD). To calculate the LCM, we have to find out the least common number which is divisible by both input numbers. For calculating LCM, we can use the following formula-

formula for calculate lcm 

For example, LCM(4,6)=12. Here 12 is the least number which is divisible by both numbers so LCM(4,6)=12.

  • First Number 4, 4*1=4, 4*2=8, 4*3=12
  • Second Number 6, 6*1=6, 6*2=12

Here, the least common term is 12, divisible by both input numbers.

Highest Common Factor(HCF)

HCF is also known as Greatest Common Divisor(GCD) or Greatest Common Factor(GCF). To calculate the HCF, we have to find out the greatest common number that can divide both input numbers. For example, HCF(4,6)=2. 2 is the greatest common number that can divide both input numbers.

Java Program to find LCM and GCD of two numbers

import java.util.*;
class test {
    public static void main(String args[]) {
        int a, b;
        System.out.println("Enter the a and b value");
        Scanner sc = new Scanner(;
        a = sc.nextInt();
        b = sc.nextInt();
        //copy the a,b values into x,y
        int x = a;
        int y = b;
        while (x != y) {
            if (x > y) {
                x = x - y;
            } else {
                y = y - x;
        /* when we exit the while loop.we get the two value x 
        and y which both are equals and this is our HCF(GCD)result.
        System.out.println("HCF of a&b=" + x);
        //Now Apply the Formula of LCM 
        System.out.println("LCM of a&b=" + ((a * b)) / x);




First of all, I am copying the original value to the temporary variable x and y because we used the original value to calculate the LCM. Now I am taking a while loop which is executed continuously till the value of a and b is not equal. Inside the while loop, we have to check which value is greater if x is greater then update the x value otherwise update the y value. Once the program comes out of the loop then we get the HCF or GCD which is nothing but an x or y value. Now we can find the LCM value with the help of a formula.


In this blog we have seen, what is LCM and GCD and how we can calculate the LCM and HCF of two numbers.

Thanks for reading and hope you like it. If you have any suggestions or queries on this blog, please share your thoughts.