File tree 1 file changed +6
-4
lines changed
src/main/java/com/thealgorithms/divideandconquer
1 file changed +6
-4
lines changed Original file line number Diff line number Diff line change 2
2
3
3
// Java Program to Implement Binary Exponentiation (power in log n)
4
4
5
+ // Reference Link: https://en.wikipedia.org/wiki/Exponentiation_by_squaring
6
+
5
7
/*
6
8
* Binary Exponentiation is a method to calculate a to the power of b.
7
9
* It is used to calculate a^n in O(log n) time.
@@ -14,14 +16,14 @@ public class BinaryExponentiation {
14
16
15
17
// recursive function to calculate a to the power of b
16
18
public static long calculatePower (long x , long y ) {
19
+ // Base Case
17
20
if (y == 0 ) {
18
21
return 1 ;
19
22
}
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 );
23
25
}
24
- return val * val * x ;
26
+ return calculatePower ( x * x , y / 2 ); // even power
25
27
}
26
28
27
29
// iterative function to calculate a to the power of b
You can’t perform that action at this time.
0 commit comments