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:
base^(exponent/2)
and square the result.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.compublic 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.