GATE / CS ARCHIVE

GATE CSE 2007 / QUESTION 44

Worst-case recursion depth of Euclid algorithm

Algorithms · Asymptotic Analysis & Recurrences · Full GATE CSE 2007 paper

GATE 2007, Q44 2 marks · MCQ
Report issue

Asymptotic Analysis & Recurrences

Question 44, GATE 2007: For the following source C-style function with n≥m, how many recursive calls are made?
int gcd(n,m) {
    if(n % m == 0) return m;
    n = n % m;
    return gcd(m,n);
}
The source does not explicitly say worst case or m>0; state those assumptions in interpreting the options.
Options:
(A) Θ(log₂ n)
(B) Ω(n)
(C) Θ(log₂ log₂ n)
(D) Θ(√n)
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Approach. This is Euclid’s algorithm. An upper bound comes from a constant-factor size reduction within two calls; a tight worst-case lower bound comes from consecutive Fibonacci arguments.

2. Derivation and interpretation. For positive integers n≥m>0, Euclid replaces (n,m) by (m,n mod m). Within two recursive steps the larger argument decreases by at least a factor of two, so there are O(log n) recursive calls. Consecutive Fibonacci inputs attain a matching lower bound: their quotients are one for most steps, and Fk grows exponentially in k, giving Θ(log n) calls in the worst case (A). The statement does not say worst case: when m divides n, there are zero recursive calls. Therefore Θ(log n) is not a pointwise bound for every input satisfying n≥m. Positive m is also necessary to avoid remainder by zero.

Original paper, page 10