0

why does it work unexpectedly ?

Please show me my mistake , for negative inputs , it does not output an expected value . class Solution { public: double myPow(double x, int n) { if(n==0){ return 1; } else if(n>0){ if(n%2==0){ double number = myPow(x,n/2); return number*number; } else{ double number = myPow(x,n/2); return x*number*number; } } else if(n<0) { if(n == -1){ return 1/x; } else{ double number = myPow(x,n/2); double r = 1/number; double r_x = 1/x; double res = r*r; double otherwise = r_x*res; if(n%2==0){ return res; } else{ return otherwise; } } } } };

30th May 2021, 4:34 PM
Ali_combination
Ali_combination - avatar
8 Respuestas
+ 1
x is 5 and n is -2 if (n < 0) // true Then number = myPow(x, n/2) = 1/5 r = 1/number = 5 res = r*r = 25 if (n%2==0) //-2%2 == 0 Then return res = 25
30th May 2021, 9:43 PM
Ore
Ore - avatar
+ 1
Ore I got the point ... thank you so much .
31st May 2021, 5:47 PM
Ali_combination
Ali_combination - avatar
0
What do you mean by unexpectedly?
30th May 2021, 4:56 PM
Eashan Morajkar
Eashan Morajkar - avatar
0
Eashan Morajkar suppose that the inputs are 5 and -2 . It outputs 25 , while it should output 1/25 .. the else if(n<0){ .. } part has some bugs..
30th May 2021, 5:02 PM
Ali_combination
Ali_combination - avatar
0
So your code just finds the square root or square
30th May 2021, 5:05 PM
Eashan Morajkar
Eashan Morajkar - avatar
0
Eashan Morajkar hmmm.. square ? I have actually made a power function which should execute in O(log(n)) ... Pow(x,n) = x^n .
30th May 2021, 5:08 PM
Ali_combination
Ali_combination - avatar
0
Ali_combination then i might not be the right person because i haven't learned it in school yet, sorry for wasting your time
30th May 2021, 5:09 PM
Eashan Morajkar
Eashan Morajkar - avatar
0
Eashan Morajkar no problem bro ... good luck
30th May 2021, 5:17 PM
Ali_combination
Ali_combination - avatar