Skip to content

Commit d086afc

Browse files
Hardvanvil02
andauthored
Enhance code density and readability (TheAlgorithms#4914)
* Enhance code density and readability * Add wiki link --------- Co-authored-by: vil02 <65706193+vil02@users.noreply.github.com>
1 parent e5f3d23 commit d086afc

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/main/java/com/thealgorithms/divideandconquer/BinaryExponentiation.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
// Java Program to Implement Binary Exponentiation (power in log n)
44

5+
// Reference Link: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
6+
57
/*
68
* Binary Exponentiation is a method to calculate a to the power of b.
79
* It is used to calculate a^n in O(log n) time.
@@ -14,14 +16,14 @@ public class BinaryExponentiation {
1416

1517
// recursive function to calculate a to the power of b
1618
public static long calculatePower(long x, long y) {
19+
// Base Case
1720
if (y == 0) {
1821
return 1;
1922
}
20-
long val = calculatePower(x, y / 2);
21-
if (y % 2 == 0) {
22-
return val * val;
23+
if (y % 2 == 1) { // odd power
24+
return x * calculatePower(x, y - 1);
2325
}
24-
return val * val * x;
26+
return calculatePower(x * x, y / 2); // even power
2527
}
2628

2729
// iterative function to calculate a to the power of b

0 commit comments

Comments
 (0)