4
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.

8
  • 2
    What is T? Is it the number of comparisons or time taken or what? Commented Jun 9, 2012 at 6:05
  • 2
    What exactly are you trying to do? Commented Jun 9, 2012 at 6:06
  • did you miss homework tag or we are in wrong way? Commented Jun 9, 2012 at 6:09
  • 2
    Are you trying to find the complexity? Commented Jun 9, 2012 at 6:13
  • @Mark ByersT is the time taken to solve this algorithm Commented Jun 9, 2012 at 6:14

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.