Print HCF of Two Integers in Java

Computations and programming when combined make a very deadly combination. As the ability to solve complex mathematical questions in itself is a great deal. But when one has to do the same thing by writing up a code, things get somewhat more complicated. Not to mention the language your coding in also determines whether it’s going to be easy to difficult. So today we’re going to write a program to print HCF of Two Integers in Java.

 

What’s The Approach? 

 

  • Let us consider a and b to be the two Integers to find HCF of.

 

  • Firstly we’ll find the gcd of these two numbers, i.e, using a condition where if a becomes zero we’ll return b

 

  • However, if that’s not the case then we’ll simply recursively return b % a, that way we’ll get a gcd as output.

 

Also Read:  Print Square Root of A Number in Java

 

Java Program To Print HCF of Two Integers

 

Input:

 

a = 98, b = 56

 

Output:

 

HCF of 98 and 56 is 14

 

// Java program to find HCF of two numbers
class TechDecodeTutorials
{
    // Recursive function to return HCF of a and b
    static int gcd(int a, int b)
    {
    if (b == 0)
        return a;
    return gcd(b, a % b);
    }
    
    // Driver method
    public static void main(String[] args)
    {
        int a = 98, b = 56;
        System.out.println("HCF of " + a +" and " + b + " is " + gcd(a, b));
    }
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *