in Algorithms retagged by
26,531 views
64 votes
64 votes

In the following C function, let $n \geq m$.

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?

  1. $\Theta(\log_2n)$

  2. $\Omega(n)$

  3. $\Theta(\log_2\log_2n)$

  4. $\Theta(\sqrt{n})$

in Algorithms retagged by
26.5k views

4 Comments

For m=2 and for all n=2^i , running time is ϴ(1) which will contradicts every option...
1
1
0
0

8 Answers

63 votes
63 votes
Best answer

Worst case will arise when both $n$ and $m$ are consecutive Fibonacci numbers.

$\text{gcd}(F_n, F_{n-1}) = \text{gcd}(F_{n-1},F_{n-2}) = \dots =  \text{gcd}(F_1,F_0) = 1$

and $n^{th}$ Fibonacci number is $1.618^n$, where $1.618$ is the Golden ratio.

So, to find $\text{gcd} (n,m)$, number of recursive calls will be  $\Theta (\log n) $.

Correct Answer: $A$

edited by

4 Comments

good to read http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibmaths.html 

- fibonacci series, got lot of properties (last digit, last 2 digit periodic etc)

-cormen 3rd ed pg 59, ex pg 108 (3rd ed), ch27 pg 776 (3rd given TC for finding ith fib number), pg 993 (given gcd has worst case when n , m are consecutive fibonacci number)

1
1
worst question by gate , i think this questions are made to leave or else you are going to lose your precious time!!!!
8
8
Yes, if you don't have sufficient background knowledge you'll lose time on such questions.
6
6
28 votes
28 votes

Try to put input in worst case...

edited by

4 Comments

Bhai, please explain @himanshu
0
0
@ankit3009  n is approaching 1  function call by function call that is we are dividing it through by 2 plot the function calls and you can observe it takessome  k function calls   those are (n/2 power k   )=1   equating it we will get logn
1
1

@ankit3009, take the worst case input like 97, 48 or whatever you wish.

And, do consider this fact (bolded):

int gcd(n,m)  {
    if (n%m == 0) return m;
    n = n%m;
    return gcd(m,n);
}

 

Give a shot, and still if you can't get, revert back with issue, more specifically where you're stuck on.

1
1
12 votes
12 votes

 

This is how I approached the Problem. 

2 Comments

Wait a minute!
0
0
how have u got this idea in the exam man😢
0
0
4 votes
4 votes
let T(m,n) be the total number of steps.

so, T(m,0) = 0,

      T(m,n) = T(n, m mod n) on average

 

=>  $T(n) = \sum :{T(k,n)} from k=0 to n$

 

by using masters theorem you will get: $ \approx \Theta (\log n)$
by

1 comment

How to solve by simple way by applying recurrence relation?
0
0
Answer:

Related questions