Write a program to find HCF (Highest Common Factors) of two numbers.

Here is a Java program to find the Highest Common Factor (HCF) of two numbers using the Euclidean algorithm. The program includes sample output as well.

				
					import java.util.Scanner;

public class HCF {
    
    // Function to find HCF using Euclidean algorithm
    public static int findHCF(int a, int b) {
        if (b == 0) {
            return a;
        }
        return findHCF(b, a % b);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input two numbers from user
        System.out.print("Enter two numbers: ");
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();

        // Find HCF
        int hcf = findHCF(num1, num2);

        // Output the result
        System.out.println("The HCF of " + num1 + " and " + num2 + " is: " + hcf);
        
        scanner.close();
    }
}

				
			

Explanation:

  1. The program defines a function findHCF that uses the Euclidean algorithm to compute the HCF.
  2. In the main method, the program takes two integer inputs from the user using a Scanner.
  3. It then calls the findHCF method with these two numbers and stores the result.
  4. Finally, it prints the HCF of the two numbers.

Sample Output:

				
					Enter two numbers: 56 98
The HCF of 56 and 98 is: 14

				
			

In this example, when the user inputs 56 and 98, the program calculates and outputs the HCF as 14.

Scroll to Top