From d086afce09a7de8d64332cc41015d3cf00e90cee Mon Sep 17 00:00:00 2001 From: Hardik Pawar <97388607+Hardvan@users.noreply.github.com> Date: Tue, 31 Oct 2023 03:48:05 +0530 Subject: [PATCH] Enhance code density and readability (#4914) * Enhance code density and readability * Add wiki link --------- Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com> --- .../divideandconquer/BinaryExponentiation.java | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java b/src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java index da45d5b9..a70b16b0 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