c++ - Implement pow(x, n) -
why function give wrong answer -1
rather right answer 1
when try this? mypow(-1.00000, -2147483648)
double quickpower(double x, int n) { if(n==0){ return 1; } if(n==1){ return x; } if(n>=2){ int res=n%2; double half=quickpower(x,n/2); return res? half*half*x: half*half; } } double mypow(double x, int n) { return n>=0? quickpower(x,n):(1/quickpower(x,-n)); }
i try run code below. "hello world" printed out. here did't specify data type still pass if statement. why?
if (-1 > 2147483648) { cout << "hello world"; }
your problem due integer overflow when calculating -n. on system (and local one) int_min
=-2147483648 , int_max
=2147483647.
so problem -(int_min)
not representable integer. can avoid issue without going higher precision integer type:
since
xn = xn+1 / x = (1/x) / x-(n+1)
we can rewrite mypow
as
double mypow(double x, int n) { return n>=0? quickpower(x,n):(1/x)/quickpower(x,-(n+1)); }
this function ok since -(int_min+1)=int_max
.
it's worth noting have mypow(0,-k)
return either +/- infinity (n=-1) or nan (n<-1). if need case consistent little more work required. in general handling of infinite / nan values tricky pow (and not "correct" in this, or original implementation) - worth man page c pow function edge cases.
Comments
Post a Comment