Skip to content

Commit 9bd5920

Browse files
committed
4.7 Power XY - Add optimal textbook sol
1 parent 2a507d4 commit 9bd5920

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

epi_judge_java/epi/PowerXY.java

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ public class PowerXY {
66
public static double power(double x, int y) {
77
// Optimal 1 - Recusrive products of squares
88
// Time Complexity - O(y); Space - O(log y) [recursion depth]
9-
if (y < 0) { // Hanlde neg. args
9+
/* if (y < 0) { // Hanlde neg. args
1010
x = 1 / x;
1111
y = y < 0 ? -y : y;
1212
}
@@ -20,7 +20,25 @@ public static double power(double x, int y) {
2020
if ((y & 1) == 0)
2121
return power(x, y/2) * power(x, y/2);
2222
23-
return power(x, y/2) * power(x, y/2) * x;
23+
return power(x, y/2) * power(x, y/2) * x; */
24+
25+
// Textbook Sol - Iterative squaring
26+
// Time complexity - O(log y); Space - O(1)
27+
double res = 1.0;
28+
if (y < 0) { // Hanlde neg. args
29+
x = 1 / x;
30+
y = y < 0 ? -y : y;
31+
}
32+
33+
while (y != 0){
34+
if ((y & 1) == 1)
35+
res *= x;
36+
37+
x *= x; // Repeated squaring
38+
y >>= 1; // Divide by 2
39+
}
40+
41+
return res;
2442
}
2543

2644
public static void main(String[] args) {

0 commit comments

Comments
 (0)