Given a function gcd(a, b) to find GCD (Greatest Common Divisor) of two number. It is also known that GCD of three elements can be found by gcd(a, gcd(b, c)), similarly for four element it can find the GCD by gcd(a, gcd(b, gcd(c, d))). Given a positive integer n. The task is to print the formula to find the GCD of n integer using given gcd() function.
Input : n = 3 Output : gcd(int, gcd(int, int)) Input : n = 5 Output : gcd(int, gcd(int, gcd(int, gcd(int, int))))
Approach: The idea is to use recursion to print the single line command. Now, to write a recursive function, say recursiveFun(n), the required string is composed of gcd(int, + recursiveFun(n – 1) + ). This means that the recursiveFun(n) should return a string that contains a call to itself and in order to evaluate that value, the recursive function will begin again for n – 1. This will, in turn, return another string with a call to n – 1 and so until n == 1 and the recursive function instead returns the string “int”.
Below is implementation of the above approach:
gcd(int, gcd(int, gcd(int, gcd(int, int))))
Time Complexity: O(N), where N is the given number.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Recursive program to print all subsets with given sum
- Recursive program to print triangular patterns
- Recursive program to print all numbers less than N which consist of digits 1 or 3 only
- Recursive Program to print multiplication table of a number
- Program to print N minimum elements from list of integers
- Bitwise recursive addition of two integers
- Print the last k nodes of the linked list in reverse order | Recursive approach
- Recursive Program for Binary to Decimal
- Recursive program to find the Sum of the series 1 - 1/2 + 1/3 - 1/4 ... 1/N
- Recursive program to generate power set
- Recursive program for prime number
- Print any pair of integers with sum of GCD and LCM equals to N
- Recursive program to find all Indices of a Number
- Recursive program to replace all occurrences of pi with 3.14 in a given string
- Program to reverse a string (Iterative and Recursive)
- Print all possible ways to write N as sum of two or more positive integers
- Recursive program to linearly search an element in a given array
- Program to count vowels in a string (Iterative and Recursive)
- Recursive program to insert a star between pair of identical characters
- C Program to Add two Integers
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.