java binary exponentiation

java binary exponentiation

Binary exponentiation (also known as exponentiation by squaring) is an efficient algorithm for calculating the exponentiation of a number in logarithmic time. It is faster than the naive approach of multiplying the base by itself repeatedly, which takes linear time.

To implement binary exponentiation in Java, you can use a recursive function that calculates the exponentiation using the following steps:

  1. If the exponent is 0, return 1 (the base to the power of 0 is always 1).
  2. If the exponent is 1, return the base (the base to the power of 1 is always the base itself).
  3. If the exponent is even, calculate base^(exponent/2) and square the result.
  4. If the exponent is odd, calculate base^((exponent-1)/2) and square the result, and then multiply it by the base.

Here is an example of how to implement binary exponentiation in Java:

refer to‮‬:lautturi.com
public class BinaryExponentiation {

    public static long pow(long base, long exponent) {
        if (exponent == 0) {
            return 1;
        }
        if (exponent == 1) {
            return base;
        }
        long half = pow(base, exponent / 2);
        if (exponent % 2 == 0) {
            return half * half;
        } else {
            return half * half * base;
        }
    }

    public static void main(String[] args) {
        long base = 2;
        long exponent = 10;
        long result = pow(base, exponent);
        System.out.println(base + "^" + exponent + " = " + result); // prints "2^10 = 1024"
    }
}

In this example, the pow() method is a recursive function that implements the binary exponentiation algorithm. The main() method calculates 2^10 and prints the result.

To run the example, create a new Java class and copy the code into it. Run the class using the java command. The output should be:

2^10 = 1024

You can also use an iterative approach to implement binary exponentiation in Java. The iterative approach is generally faster and uses less stack space, but it is less intuitive than the recursive approach.

Created Time:2017-11-03 00:14:45  Author:lautturi