Enhance code density and readability (#4914)

* Enhance code density and readability

* Add wiki link

---------

Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
This commit is contained in:
Hardik Pawar 2023-10-31 03:48:05 +05:30 committed by GitHub
parent e5f3d232c9
commit d086afce09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,6 +2,8 @@ package com.thealgorithms.divideandconquer;
// Java Program to Implement Binary Exponentiation (power in log n) // 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. * 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. * 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 // recursive function to calculate a to the power of b
public static long calculatePower(long x, long y) { public static long calculatePower(long x, long y) {
// Base Case
if (y == 0) { if (y == 0) {
return 1; return 1;
} }
long val = calculatePower(x, y / 2); if (y % 2 == 1) { // odd power
if (y % 2 == 0) { return x * calculatePower(x, y - 1);
return val * val;
} }
return val * val * x; return calculatePower(x * x, y / 2); // even power
} }
// iterative function to calculate a to the power of b // iterative function to calculate a to the power of b