-2

I'm doing some homework and I'm struggling with a specific question. There is a similar question in my assignment so I need to get the hang of this.

Here's the code:

    public static double power2(double base, int n) {
    switch (n) {
        case 1:
            return base;
        case 2:
            return base * base;
        default:
            if (n % 2 == 0) /* n is even */ {
                return power2(power2(base, n / 2), 2);
            } else /* n is odd */ {
                return power2(power2(base, n / 2), 2) * base;
            }
    }
}

I have the base case, which I believe to be 0, n=1; However, getting to T(n) is where I'm struggling.

It needs to be similar T(n-1)+c, n>1.

I need to express the code with a recursive formula.

Can anyone ELI5 this for me?

Sarah vd Byl
  • 223
  • 3
  • 11

1 Answers1

2

I'm tempted to say the recurrence is

T(n) = T(n/2) + O(1)

If you rewrite the general case as

double temp = power2(base, n/2); // T(n/2)
if (n%2 == 0) {
  return power2(temp, 2); // O(1) by looking at the base case
} else {
  return power2(temp, 2) * base; // O(1) by looking at the base case
}

which makes it

O(log(n))

This document covers the specific problem you're looking at. They're probably doing a better job than I am, I haven't looked at the master theorem in a long time.

Vlad
  • 18,195
  • 4
  • 41
  • 71
  • So if it is stipulated that it takes *c* units of time to do a multiplication, the recurrence would be 'T(n) = T(n/2) + c' ? Would multiplying by the base an extra time when the number is odd make it *2c*? Regardless, thanks for your help! – Sarah vd Byl Aug 28 '15 at 13:07
  • Ah, I missed that part. I suppose in the n-is-odd case, it would be 2c, one c for the n=2 base case, and then another c for the `*base` at the end. – Vlad Aug 28 '15 at 13:10
  • 1
    Right. That makes sense. Thanks a bunch. – Sarah vd Byl Aug 28 '15 at 13:11