You are here: Home / Topics / Program to find HCF and LCM of two numbers in Java

Program to find HCF and LCM of two numbers in Java

Filed under: Java on 2023-08-18 06:51:38

 

// Program to find HCF and LCM of Two given Number.

import java.util.Scanner;

class  HcfAndLcmExample
{
public static void main( String args[ ] )
{
 int a, b, i, s, hcf=0, lcm=0;
 Scanner sc = new Scanner( System.in );
 
 System.out.print( " Enter First Number : " );
 a = sc.nextInt();
 System.out.print( " Enter Second Number : " );
 b = sc.nextInt();

 if( a < b )
  s = a;
 else
  s = b;
  
 for( i=1 ; i<=s ; i++ )
 {
  if(( a%i == 0 )&&( b%i == 0))
  {
   hcf = i;
  }
 }
 
 System.out.println( " HCF : " + hcf );
 lcm = ( a * b ) / hcf;
 System.out.println( " LCM : " + lcm );
}
}


Output:

Enter First Number : 18
Enter Second Number : 12
HCF : 6
LCM : 36

 

Note: scanner class is used to take Input from the user.

About Author:
Y
Yatendra Sir     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.