File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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 ) {
You can’t perform that action at this time.
0 commit comments