An efficient algorithm for finding the power of a positive integer

  • 2020-04-01 02:07:23
  • OfStack

The core idea is
When n is even, a to the n is equal to a to the n over 2 times a to the n over 2
When n is odd, a to the n is equal to a to the n minus 1 over 2 times a to the n minus 1 over 2& PI; * a.
The code is 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 the right shift operation to replace dividing by 2, and USES the bit and operation to replace the odd-even judgment, so that the algorithm is much more efficient.

Related articles: