In this, we are going to calculate Greatest Common Divisor, using Functions.
The Code given below can be used in TURBO C++ Compilers: -
#include <stdio.h>
#include<conio.h>
int gcd(int a, int b)
{
if (a == 0)
{
return b; // b is the GCD
}
if (b == 0)
{
return a; // a is the GCD
}
if (a == b) // The case of equal numbers
{
return a; // return any one of them, doesn't matter
}
// Apply case of subtraction
if (a > b) // if a is greater subtract b
{
return gcd(a - b, b);
}
return gcd(a, b - a); //otherwise subtract a
}
void main()
{
clrscr();
int a, b;
cout << "Enter 1st number : ";
cin >> a;
cout << "Enter 2nd number : ";
cin >> b;
cout << "GCD of " << a << " and " << b << " is " << gcd(a, b);
getch();
}
//...........Coded by Rishab Nair
The Code given below can be used in gcc/g++ Compilers: -
#include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (a == 0)
{
return b; // b is the GCD
}
if (b == 0)
{
return a; // a is the GCD
}
if (a == b) // The case of equal numbers
{
return a; // return any one of them, doesn't matter
}
// Apply case of subtraction
if (a > b) // if a is greater subtract b
{
return gcd(a - b, b);
}
return gcd(a, b - a); //otherwise subtract a
}
int main()
{
int a, b;
cout << "Enter 1st number : ";
cin >> a;
cout << "Enter 2nd number : ";
cin >> b;
cout << "GCD of " << a << " and " << b << " is " << gcd(a, b);
return 0;
}
//...........Coded by Rishab Nair
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP