I don’t see how this method would be used 31 times when I try to recursively calculate 2^8.
Does this method calculate powers in O(logN) complexity?
When I run it the output is:
0
1
2
3
4
5
...
29
30
2^8 is: 256
Code
private static int power(int x, int y)
{
System.out.println(step++);
if (y == 0)
return 1;
return power(x, y/2) * power(x, y/2);
}
Here you’re actually making two calls to the power method with the same values:
Instead, you could make half as many calls if you write it like this:
If we walk through your original example, we will make 31 calls, which is what you see (0 to 30). Walk through your code to see why: