Java Program to find LCM and HCF of any two integer numbers

Here we are explaining how to write a java program to find out the LCM and HCF of any two integer numbers. So first we have to read two integer numbers from the user and by using a while loop we will calculate the LCM and HCF.

What is LCM?

LCM  means the Least Common Multiplier. The LCM of two integer numbers and b are The lowest positive integer that can be divided by a and b.

Example: The LCM of 10 and 12 is shown below.


What is HCF?

HCF  means the Highest common Factor. The HCF of two integer numbers a and b are, The highest positive integer that can be divided by a and b.

Example: The HCF of 10 and 12 is shown below.


How to implement the java program to find out HCF and LCM?

First, we have to declare the class LCM_HCF. Then declare the variables. Create an object of the scanner class and read numbers into the variable a and b.Assign temp1=a,temp2=b.By using while loop with the condition temp2!=0 assign temp=temp2,temp2=temp1 mod temp2,temp1 =temp.Assign HCF as temp1.Calculate LCM as (a*b)/HCF.Then display HCF as HCF and LCM as LCM using System.out.println().



STEP 1: Declare the class LCM_HCF with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variables temp1,temp2,a,b,temp,HCF,LCM.

STEP 4: Read the first number into the variable a.

STEP 5: Read the second number into the variable b

STEP 6: Assign temp1=a,temp2=b.

STEP 7: By using a while loop check temp2!=0 then assign temp=temp2,temp2=temp1%temp2,temp1=temp.

STEP 8: Assign HCF as temp1.

STEP 9: Calculate LCM as (a*b)/HCF.

STEP 10: Display HCF as HCF and LCM as LCM.


Java Source Code

                                          import java.util.Scanner;

public class LCM_HCF{
   public static void main(String args[]){
      int temp1, temp2, a,b,temp,HCF,LCM;
      Scanner sc = new Scanner(;

      System.out.println("Enter the first Number: ");
      a= sc.nextInt();
      System.out.println("Enter the Second Number: ");
      b= sc.nextInt();

      temp1 = a;
      temp2 = b;

      while(temp2 != 0){
         temp = temp2;
         temp2 = temp1%temp2;
         temp1 = temp;

      HCF = temp1;
      LCM = (a*b)/HCF;

      System.out.println("HCF = "+HCF);
      System.out.println("LCM =  "+LCM);


Enter the first Number: 5
Enter the Second Number: 10
HCF = 5
LCM =10