Search
• Yogeeta Paryani

# JAVA| Java program to calculate HCF of two numbers.

In this blog we're going to calculate HCF of two no. using java.

An H.C.F or Highest Common Factor, is the largest common factor of two or more values.

For eg. Factors of 9 and 6 are-

9 - 1,3,9

6 - 1,2,3,6

The common factors are 1, 3 and the highest common factor is 3.

IMPLEMENTATION:

1. Import Scanner library then create class, now under main class define two variables you want HCF for and also define variable i and hcf.

``` import java.util.Scanner;
class Hcf
{
public static void main(String args[])
{
int n1,n2,i,hcf=0;

```

2. Now take the value of numbers from user.

```Scanner sc=new Scanner(System.in);
System.out.print("Enter first no.");
n1=sc.nextInt();
System.out.print("Enter Second no.");
n2=sc.nextInt();

```

3. Create a loop from 1 to maximum of numbers.

``` for(i=1;i<=n1||i<=n2;i++)
{```

4. Check if both are completely divided by same loop number, if yes, store it

``` if(n1%i==0&&n2%i==0)
{
hcf=i;
}
}```

5. Display the stored number is HCF

``` System.out.println("HCF of given two no. is="+hcf);
}
}```

OUTPUT:

```Enter first no.9
Enter Second no.6
HCF of given two no. is=3```

Happy Coding!

Please write comments if you find any bug in the above code/algorithm, or find other ways to solve the same problem.

26 views

See All