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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.