Had a question on how to reduce the amount of recursive calls on a self implementation of the pow method. Here is what I wrote, can this be improved?
public static int pow(double a, int b) {
boolean isNegative = false;
if(b < 0) {
isNegative = true;
}
if(b == 0) {
return 1;
}
else if(b == 1) {
return (isNegative ? (1 / b) : b);
}
return (isNegative ? ((1 / b) * (1 / b) * pow(a, b + 2)) : (b * b * pow(a, b - 2)));
}
Yes, it can be improved.
Think about it this way:
Code (brain-compiled, coffee hasn’t kicked in yet, etc.):
This gives you O(log b) recursive calls, as opposed to O(n) in your solution.