### Find the HCF of 2 numbers using Java code

What is HCF - its the Highest Common Factor of two numbers. Which means it is the biggest number which divides two numbers such that the remainder is 0.

What will be utilized in this logic:

1. While loop to iterate till we arrive at the solution

2. % Operator to find the remainder

Let's check the code!

/** * Find the HCF of two numbers * @author computengine.com * @param num1 * @param num2 * @return */ public static void findHCF(int num1, int num2) { int remainder = 0; System.out.println("Input Num1:"+num1); System.out.println("Input Num2:"+num2); //loop till we find a number which divides exactly while (num1 % num2 > 0) { //find the remainder of the division remainder = num1 % num2; System.out.println("Remainder:"+remainder); //put num2 in num1 num1 = num2; System.out.println("Num1:"+num1); //put remainder in num2 num2 = remainder; System.out.println("Num2:"+num2); } System.out.println("HCF found:"+num2); }

As you can see, we will use the % operator in the while loop and continue the loop till we find a 0 which means fully divisible.

Now, we will find the remainder of the division of number 1 and number 2. And swap number 1 with number 2. Store the Remainder in number 2, and continue the loop till we hit a 0 in division. The first number which gives a 0 in the remainder will be the HCF.

Why have we taken this approach? Well, we are simply replicating the Division method of finding HCF and making our code follow the exact same steps.

Easy isn't it!

Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on Facebook, Twitter, Tumblr.

## Comments

## Post a Comment