# Recursive program to print formula for GCD of n integers in C++

We are given an integer as input. The goal is to print the formula of GCD of n numbers using recursion.

We know that the GCD of three numbers say a1,b1 and c1 will be gcd(a1,gcd(b1,c1)).Similarly for more than three numbers, gcd can be obtained by formula as gcd ( a1,gcd(b1,gcd(c1…..,gcd(y1,z1)).

## Examples

Input − Num = 4;

Output − Formula is:

GCD(int a3, GCD(int a2, GCD(int a1, int b1)))

Input − Num = 6;

Output − Formula is: GCD(int a5, GCD(int a4, GCD(int a3, GCD(int a2, GCD(int a1, int b1)))))

## Approach used in the below program is as follows

In this approach we are using the recursive function gcdFormula(int num1) which takes count of numbers as input and returns string containing the formula of gcd for num1 numbers.

For base cases-: if num1 is 1 return string "int b"+to_string(num1)+"".

Else-: Recurse again for gcdFormula(num1-1) and appending previous string.

• Take the input number Num.

• Function gcdFormula(int num1) which takes count of numbers as input and returns string containing the formula of gcd for num1 numbers

• If num1 is 1 then return string "int b"+to_string(num1)+"".

• Else print "GCD(int a"<<num1-1<<", ";

• Followed by recursion step as return (gcdFormula(num1 - 1)+")")

• At the end the whole string will be returned.

• Print result obtained inside main.

## Example

#include <bits/stdc++.h>
using namespace std;
string gcdFormula(int num1){
if (num1 == 1){
return ("int b"+to_string(num1)+"");
}
else{
cout<<"GCD(int a"<<num1-1<<", ";
return (gcdFormula(num1 - 1)+")");
}
}
int main(){
int Num = 6;
cout<<"Formula is :"<<endl;
cout<<gcdFormula(Num);
return 0;
}

## Output

If we run the above code it will generate the following Output

Formula is :
GCD(int a6, GCD(int a5, GCD(int a4, GCD(int a3, GCD(int a2, GCD(int a1, int b1))))))