Write a program to calculate GCD of 2 number (i) with recursion (ii) without recursion

by

Last updated on Nov 19, 2022
DS Practicals (Question 13)

Input (with recursion)

#include<iostream>
#include <stdio.h>

using namespace std;

int GCD(int a, int b);
int main() 
{
    cout << "\n\t ~~~~~~~~~~~~~~~~~~~~~~~Practical 13 WITH RECURSION~~~~~~~~~~~~~~~~~~~~\n\t\t\t\t  \n";
    int a, b;
    cout<<"\nEnter the first integer: ";
    cin>>a;
    cout<<"\nEnter the second integer: ";
    cin>>b;
    cout<<"\nG.C.D of "<<a<<" and "<<b<<" is:\n"<<GCD(a, b);
    return 0;
}

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

Input (without recursion)

#include<iostream>
#include <stdio.h>

using namespace std;
 
int GCD(int a, int b);
 
int main()
{
    cout << "\n\t ~~~~~~~~~~~~~~~~~~~~~~~Practical 13 WITHOUT RECURSION~~~~~~~~~~~~~~~~~~~~\n\t\t\t\t  \n";
    int a, b, G;
 
    cout<<"\nEnter the first number:";
    cin>>a;
    cout<<"\nEnter the second number:";
    cin>>b;
    
    G =GCD(a, b);
    cout<<"The GCD of "<<a<<" and "<<b<<"is :"<<G;
 
    return 0;
}
 
int GCD(int a, int b)
{
    while (a != b)
    {
        if (a > b)
        {
            a = a - b;
        }
        else
        {
            b = b - a;
        }
    }
    return a;
}

How useful was this post?

5 star mean very useful & 1 star means not useful at all.

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Tags: