C program to find GCD or HCF of two numbers

GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them.

For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14.

Euclidean algorithm is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.

C

#include <stdio.h>

// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    // Everything divides 0 
    if (a == 0 || b == 0)
       return 0;

    // base case
    if (a == b)
        return a;

    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}

// Driver program to test above function
int main()
{
    int a = 98, b = 56;
    printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
    return 0;
}

Java

// Java program to find factorial of given number
class Test
{
	// Recursive function to return gcd of a and b
	static int gcd(int a, int b)
	{
	    // Everything divides 0 
	    if (a == 0 || b == 0)
	       return 0;
	 
	    // base case
	    if (a == b)
	        return a;
	 
	    // a is greater
	    if (a > b)
	        return gcd(a-b, b);
	    return gcd(a, b-a);
	}
	
    // Driver method
    public static void main(String[] args) 
    {
    	int a = 98, b = 56;
        System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b));
    }
}


Output:
GCD of 98 and 56 is 14

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.