ADVERTISEMENT
ADVERTISEMENT

Java program to calculate HCF of two numbers

Given two numbers, we have to write a Java program to calculate HCF of the given numbers.
Submitted by Nidhi, on February 23, 2022

Problem Solution:

In this program, we will read two integer numbers and find the Highest Common Factor (HCF) for both numbers.

Program/Source Code:

The source code to calculate the HCF of two numbers is given below. The given program is compiled and executed successfully.

// 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

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, we created a public class Main. It contains two static methods CalHcf() and main().

The CalHcf() method is used to calculate the HCF of given numbers and return the result to the calling method.

The main() method is an entry point for the program. And, we read two integer numbers from the user using the nextInt() method. Then we called CalHcf() method to calculate HCF and printed the result.

Java Basic Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.