C/C++ Program to Find GCD of Two Numbers Using Recursion

In this program we will use recursion and Euclid’s algorithm to find greatest common divisor of two numbers. The definition of Euclid’s algorithm is as follows:

Also Read: C program to find factorial of any number using recursion
Also Read: How to Convert a Recursive Function or Algorithm to Non-Recursive?

C Program

#include<stdio.h>

int gcd(int n,int m)
{
    if((n>=m)&&((n%m)==0))
        return(m);
    else
        gcd(m,(n%m));
}

int main()
{
    int n,m,result;
    printf("Input the first integer number:");
    scanf("%d",&n);
    printf("Input the second integer number:");
    scanf("%d",&m);
    result=gcd(n,m);
    printf("nGCD of %d and %d is %d",n,m,result);

    return 0;
}

C++ Program

#include<iostream>
#include<cstdlib>

using namespace std;

int gcd(int n,int m)
{
    if((n>=m)&&((n%m)==0))
        return(m);
    else
        gcd(m,(n%m));
}

int main()
{
    int n,m,result;
    cout<<"Input the first integer number:";
    cin>>n;
    cout<<"Input the second integer number:";
    cin>>m;
    result=gcd(n,m);
    cout<<"nGCD of "<<n<<" and "<<m<<" is "<<result;

    return 0;
}

C/C++ Program to Find GCD of Two Numbers Using Recursion

4 thoughts on “C/C++ Program to Find GCD of Two Numbers Using Recursion”

  1. hoe to write it in coino.h mean not that one which u write above of C++ in simple if or if else statment

  2. No need of checking greater number, you can get the same result as below:

    int GCD(int a, int b)
    {
    if (a == 0)
    return b;
    return GCD(b%a, a);
    }

  3. I wanted to ask whether this website only uses the 2 programming languages only cause I do need to ask other languages. Thank you

Leave a Comment

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