Java Program to Calculate HCF of Two Numbers

You are currently viewing Java Program to Calculate HCF of Two Numbers

Java program to calculate HCF of two numbers

// Java program to calculate the 
// HCF of two numbers

import java.util.Scanner;

public class Main {
  static int CalHcf(int num1, int num2) {
    int temp = 0;

    if (num1 == 0 || num2 == 0)
      return 0;

    while (num2 != 0) {
      temp = num1 % num2;
      num1 = num2;
      num2 = temp;
    }
    return num1;
  }

  public static void main(String[] args) {
    int num1 = 0;
    int num2 = 0;
    int hcf = 0;

    Scanner myObj = new Scanner(System.in);

    System.out.printf("Enter first number: ");
    num1 = myObj.nextInt();

    System.out.printf("Enter second number: ");
    num2 = myObj.nextInt();

    hcf = CalHcf(num1, num2);
    System.out.printf("HCF of %d,%d is: %d\n", num1, num2, hcf);
  }
}

Output

Enter first number: 40
Enter second number: 100
HCF of 40,100 is: 20

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