Solution:
Basically, it is a math problem.
if n is even pow(x,n) =pow(x,n/2) * pow(x,n/2);
if n is odd, a) if n is positive pow(x,n)=pow(x,n/2) * pow(x,n/2) * x;
b) if n is negative pow(x,n)=pow(x,n/2) * pow(x,n/2) /x;
public double pow(double x, int n) {
if (n == 0) return 1.0;
double half = pow(x, n/2);
if (n%2 == 0) return half*half;
else if (n>0) return half*half*x;
else return half/x*half;
}
No comments:
Post a Comment