1

So this is the code:

int test ( int n) 
{ 
   if (n ≤2) return 1; 
   else return test(n-2) * test(n-2); 
} 

I'm not confident in how to reason about this recursive function. I tried mapping the N value to the recursion depth like so:

N = 2 -> 0 recursions
N = 4 -> 2
N = 8 -> 14

But to be honest I'm not sure this gets me anywhere (and just thinking about test(16) hurts my head.

1
  • you know that you can make the method much more efficient by changing return test(n-2) * test(n-2) into { int y=test(n-2); return y*y; }? A single trivial change can turn a O(2^n) function into an O(n) function. Commented Jan 17, 2016 at 13:22

1 Answer 1

2

Let's start by writing out a recurrence relation for the total number of calls made:

  • T(0) = T(1) = T(2) 1, since there's one total call (the initial call).
  • T(n+2) = 2T(n) + 1, since there's one call for the initial call, plus two recursive calls to problems of size n.

Let's start by looking at the case where n is even. Then

  • T(0) = 1
  • T(2) = 1
  • T(4) = 2T(2) + 1 = 3
  • T(6) = 2T(4) + 1 = 7
  • T(8) = 2T(6) + 1 = 15
  • T(9) = 2T(8) + 1 = 31

Except for the 0 case, it looks like these values take on the pattern 1, 3, 7, 15, 31, etc. Notice that each of these is one less than a power of two: 1 = 2 - 1, 3 = 4 - 1, 7 = 8 - 1, etc. We can guess that what we're looking at has something to do with powers of two.

Going back to our sequence, we might make a guess that

  • T(2) = 1 = 21 - 1
  • T(4) = 3 = 22 - 1
  • T(6) = 7 = 23 - 1
  • ...
  • T(2n) = 2n - 1

So if n is even, we have T(n) = 2n/2 - 1 = (√2)n - 1. You can formalize this using a proof by induction.

For the odd case, we basically get the same thing:

  • T(1) = 1
  • T(3) = 2T(1) + 1 = 3
  • T(5) = 2T(3) + 1 = 7
  • T(7) = 2T(5) + 1 = 15
  • T(9) = 2T(7) + 1 = 31
  • ...
  • T(2n+1) = 2n - 1

So if n is even, then T(n) = 2(n-1)/2 - 1. Again, you can prove this by induction to formalize things if you'd like.

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

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.