Thursday , 30 March 2017
Home » Class 10 » Java program to find the HCF (GCD) of two numbers

Java program to find the HCF (GCD) of two numbers

Question:

Write a Program in Java to input 2 numbers and find their Highest Common Factor (HCF).

Note: If the 2 numbers are 54 and 24, then the divisors (factors) of 54 are: 1, 2, 3, 6, 9, 18, 27, 54.

Similarly the divisors (factors) of 24 are: 1, 2, 3, 4, 6, 8, 12, 24.

The numbers that these two lists share in common are the common divisors (factors) of 54 and 24: 1, 2, 3, 6.

The greatest (highest) of these is 6. That is the greatest common divisor or the highest common factor of 54 and 24.

Programming Code [Method 1]:

/**
* The class Hcf inputs two numbers and finds their HCF
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.io.*;
class Hcf
    {
        public static void main(String args[])throws IOException
        {
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter the First no : ");
            int n1=Integer.parseInt(br.readLine());
            System.out.print("Enter the Second no : ");
            int n2=Integer.parseInt(br.readLine());
            int hcf=0;
            int min = Math.min(n1,n2);
            
            for(int i=min; i >= 1; i--)
            {
                if(n1%i == 0 && n2%i == 0)
                {
                    hcf = i;
                    break;
                }
            }        
            System.out.print("\nThe hcf of "+n1+" and "+n2+" = "+hcf);
        }
    }

Output:

Enter the First no : 54
Enter the Second no : 24

The hcf of 54 and 24 = 6

Check Also

[Question 1] ISC 2017 Computer Practical Paper Solved – Box Packing

Solution of Program 1 of ISC 2017 Computer Science Paper 2 (Practical) Exam. Java program to input number of boxes to be packed and display the break-up of the cartons used in descending order of capacity

9 comments

  1. THANKS a lot

  2. Thanks a lot for the program.

  3. very nice expanation and easy to understand approach.

  4. tthanks for the code.

  5. THANK YOU BEST SITE EVER FOR ALL THE SCIENCE AND COMPUTER SUBJECTS

  6. thankyou for this program

  7. thank you so much for this program.

  1. Pingback: Java Program To Find The GCD/HCF And LCM Of Two Numbers (Division Method) | LakshyaTutorial

  2. Pingback: Java program to find the GCD of two numbers (Division Method) | Guide For School

Leave a Reply to Pradumn Cancel reply

Your email address will not be published. Required fields are marked *