diff --git a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java index da45d5b90..a70b16b0d 100644 --- a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java +++ b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java @@ -2,6 +2,8 @@ package com.thealgorithms.divideandconquer; // Java Program to Implement Binary Exponentiation (power in log n) +// Reference Link: https://en.wikipedia.org/wiki/Exponentiation_by_squaring + /* * Binary Exponentiation is a method to calculate a to the power of b. * It is used to calculate a^n in O(log n) time. @@ -14,14 +16,14 @@ public class BinaryExponentiation { // recursive function to calculate a to the power of b public static long calculatePower(long x, long y) { + // Base Case if (y == 0) { return 1; } - long val = calculatePower(x, y / 2); - if (y % 2 == 0) { - return val * val; + if (y % 2 == 1) { // odd power + return x * calculatePower(x, y - 1); } - return val * val * x; + return calculatePower(x * x, y / 2); // even power } // iterative function to calculate a to the power of b