## Find HCF of Two Numbers in Java Here, You are going to see the article with the concept of Find HCF of Two Numbers in Java program. Initially, I wish to explain about HCF of two numbers and how to do a task using the java program? Let’s see the possibilities.

Contents

## What is HCF of two numbers?

HCF stands for Highest Common Factor also known as GCD (Greatest Common factor). It is nothing but the largest number which will be perfectly divisible by two numbers.

For example, If we can choose the two numbers like “12” and “16” then the HCF of those two numbers is “4”. A number “4” is the largest common number that will be a divisor of “12” and “16”.

## Find HCF of Two Numbers in Java

We can see the example program to perform a task below.

``````import java.util.Scanner;
public class GCDOfTwoNumbers {
public static void main(String args[]){
int a, b, i, hcf = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter first number :: ");
a = sc.nextInt();
System.out.println("Enter second number :: ");
b = sc.nextInt();

for(i = 1; i <= a || i <= b; i++) {
if( a%i == 0 && b%i == 0 )
hcf = i;
}
System.out.println("HCF of given two numbers is ::"+hcf);
}
}``````

## Program Execution

Initially, We need to import the java.util.scanner() class into this program. Secondly, We have to declare the three variables to store the input numbers. After running this program, The program asks you to enter the two numbers using the new scanner() function.

After entering the inputs, The for loop iterates from 1 to the maximum values of both “a” and “b”. Later, The if…condition will check whether the two numbers are perfectly divisible by the same loop numbers.

If it is evenly divisible then the HCF of two numbers output will print on the result screen using the system.out.printIn() function.

`Read Also : Find LCM of Two Numbers in Java`

## Note

We have already published an article about Find HCF Of Two Numbers in PHP on our webpage. If you want to learn then refer to it.

## Output

Below, I’ll provide the output of “Find HCF of Two Numbers in Java” for your reference.

``````Enter first number :: 8
Enter second number :: 16
HCF of given two numbers is ::8``````

## Final Thoughts

I hope this article helps you to find HCF of two numbers in Java Program. If you face any issues please let me know via the comment section. Share this article with other Java program developers via social networks. Thank You!

### Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.