In the following C function, let .
int gcd(n,m) {
if (n%m == 0) return m;
n = n%m;
return gcd(m,n);
}
How many recursive calls are made by this function?
View worked solution
Answer: A
The given C function implements the classic Euclidean algorithm for computing the Greatest Common Divisor (GCD) of two integers and (where ).
Let's analyze the reduction in each step of the recursion:
- In the first call, if , the function terminates immediately with recursive calls.
- Otherwise, it updates and makes a recursive call
gcd(m, n).
To find the upper bound on the number of recursive steps, we consider the worst-case input. The worst-case behavior of the Euclidean algorithm occurs when and are consecutive Fibonacci numbers:
For consecutive Fibonacci numbers, each step reduces the pair to the next smaller pair of Fibonacci numbers:
This requires exactly recursive steps to reach the base case.
Using the approximation for Fibonacci numbers via the golden ratio :
Thus, the number of recursive steps in the worst case is proportional to , which is because the base of the logarithm only changes the complexity by a constant factor.
Therefore, the number of recursive calls is .
Free practice · Your answers on this page are not saved.
