Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to solve recursion of given algorithm?

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

I solved this and i got

T(n, m) = 1 + T(m, n%m)  if n > m
        = 1 + T(m, n)    if n < m
        = m              if n%m == 0

I am confused how to proceed further to get the final result. Please help me to solve this.

like image 918
devsda Avatar asked Jan 16 '23 11:01

devsda


2 Answers

The problem here is that the size of the next values of m and n depend on exactly what the previous values were, not just their size. Knuth goes into this in detail in "The Art of Computer Programming" Vol 2: Seminumerical algorithms, section 4.5.3. After about five pages he proves what you might have guessed, which is that the worst case is when m and n are consecutive fibonacci numbers. From this (or otherwise!) it turns out that in the worst case the number of divisions required is linear in the logarithm of the larger of the two arguments.

After a great deal more heavy-duty math, Knuth proves that the average case is also linear in the logarithm of the arguments.

like image 163
mcdowella Avatar answered Jan 25 '23 18:01

mcdowella


mcdowella has given a perfect answer to this.

For an intuitive explaination you can think of it this way,

if n >= m, n mod m < n/2;

This can be shown as,

if m < n/2, then: n mod m < m < n/2

if m > n/2, then: n mod m = n-m < n/2

So effectively you are halving the larger input, and in two calls both the arguments will be halved.

like image 36
sukunrt Avatar answered Jan 25 '23 19:01

sukunrt