The core idea is
When n is an even number, a^n = a^n/2 × a^n/2
When n is an odd number, a^n = a^(n-1)/2 × a^(n-1)/2 × a
The code is as follows:
Copy the code code as follows:
public class Power {
public static void main(String[] args) {
System.out.println(power(5.5,5));
}
private static double power(double base, int exponent) {
if (exponent == 0)
return 1;
if (exponent == 1)
return base;
double result = power(base, exponent >> 1);
result *= result;
if ((exponent & 0x1) == 1)
result *= base;
return result;
}
}
The code also uses a right shift operation to replace dividing by 2, and a bitwise AND operation to replace the remainder to determine parity, which makes the algorithm much more efficient.