Java Program to Calculate the Highest Common Factor of Two Numbers Using Recursion

You are currently viewing Java Program to Calculate the Highest Common Factor of Two Numbers Using Recursion

Java program to calculate the Highest Common Factor of two numbers using recursion

// Java program to calculate the Highest Common Factor 
// of two numbers using the recursion

import java.util.*;

public class Main {
  public static int calculateHCF(int num1, int num2) {
    while (num1 != num2) {
      if (num1 > num2)
        return calculateHCF(num1 - num2, num2);
      else
        return calculateHCF(num1, num2 - num1);
    }
    return num1;
  }

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

    int num1 = 0;
    int num2 = 0;
    int res = 0;

    System.out.printf("Enter number1: ");
    num1 = X.nextInt();

    System.out.printf("Enter number2: ");
    num2 = X.nextInt();

    res = calculateHCF(num1, num2);
    System.out.printf("HCF is: " + res);
  }
}

Output

Enter number1: 45
Enter number2: 75
HCF is: 15

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply