Find the HCF of 2 numbers using Java code

 


Today we'll try to solve a common mathematical question using Java code. We will find the HCF of two numbers. 

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 FacebookTwitterTumblr. 

Comments

Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to read Excel File and Load into Array

Java Program to Read a Properties file and return a Property Value

4 ways to add New Line Character to a String in Java