Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to find GCD of numbers using recursive function
The greatest common divisor (GCD) of two numbers is the largest positive integer that divides both numbers evenly. In C programming, we can find the GCD using the Euclidean algorithm implemented with a recursive function.
Syntax
unsigned int GCD(unsigned i, unsigned j);
Algorithm
The recursive GCD algorithm follows these steps −
Step 1 − Define the recursive function.
Step 2 − Read the two integers a and b.
Step 3 − Call recursive function with the following logic:
a. if j > i then return GCD(j, i) b. if j == 0 then return i c. else return GCD(j, i % j)
How It Works
The algorithm uses the Euclidean method: GCD(a, b) = GCD(b, a mod b). The recursion continues until one number becomes zero, at which point the other number is the GCD.
Flow Chart
Example
Following is the C program to find the greatest common divisor (GCD) for the given two numbers by using the recursive function −
#include <stdio.h>
unsigned int GCD(unsigned i, unsigned j);
int main() {
int a, b;
printf("Enter the two integers:
");
scanf("%d%d", &a, &b);
printf("GCD of %d and %d is %d
", a, b, GCD(a, b));
return 0;
}
/* Recursive Function*/
unsigned int GCD(unsigned i, unsigned j) {
if (j > i)
return GCD(j, i);
if (j == 0)
return i;
else
return GCD(j, i % j);
}
Enter the two integers: 48 18 GCD of 48 and 18 is 6
Time Complexity
The time complexity of the recursive GCD algorithm is O(log min(a,b)) where a and b are the input numbers. The space complexity is O(log min(a,b)) due to the recursion stack.
Conclusion
The recursive approach to finding GCD using the Euclidean algorithm provides an elegant and efficient solution. The algorithm repeatedly applies the principle that GCD(a,b) = GCD(b, a mod b) until one number becomes zero.
