Wednesday 27 January 2016

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.

import java.util.*;
class Hcf
    {
        public static void main(String args[ ])
        {
            int n1, n2, hcf=0, min, i;           
            Scanner sc=new Scanner(System.in);
            System.out.print("Enter the First no : ");
            n1=sc.nextInt();
            System.out.print("Enter the Second no : ");
            n2=sc.nextInt();
            min = Math.min(n1,n2);       
            for(i=min; i >= 1; i--)
            {
                if(n1 % i == 0 && n2 % i == 0)
                {
                    hcf = i;
                    break;
                }
            }       
            System.out.println("The HCF of " + n1 + " and " + n2 + " = " + hcf);
        }
    }


Output:
Enter the First no : 54
Enter the Second no : 24
The hcf of 54 and 24 = 6

No comments:

Post a Comment