The Greatest Common Divisor (G.C.D), also known as the greatest common factor or highest common factor, is a key concept in mathematics and computer programming. It refers to the largest number that can completely divide two or more integers without leaving a remainder. In programming, calculating G.C.D is a common task and can be efficiently tackled using recursive functions in C.
In this article, you will learn how to implement a recursive function to find the G.C.D of two numbers in C. Explore the recursive approach through clear examples, supporting you to understand and apply this method in various programming scenarios involving mathematical computations.
If the second number is zero, return the first number as the G.C.D.
If not, recursively call the G.C.D function with the second number and the remainder of the first number divided by the second.
int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
This function checks if b
is zero. If true, it returns a
as the G.C.D. Otherwise, it makes another recursive call with b
and a % b
until b
becomes zero.
Include the necessary standard I/O library.
Implement the recursive G.C.D function.
Write a main
function to take user input and display the G.C.D.
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
printf("G.C.D of %d and %d is %d\n", num1, num2, gcd(num1, num2));
return 0;
}
This program prompts the user to enter two integers. It then calculates the G.C.D using the gcd
function and displays the result.
gcc
.Using recursion to find the G.C.D of two numbers in C demonstrates the power and elegance of recursive functions for solving mathematical problems. By following the examples provided, you have a robust template to compute G.C.D in your C programs. This approach not only simplifies the code but also improves its readability, making it easier to debug and maintain. Continue practicing with different scenarios to gain more confidence in using recursion and other C programming techniques.