Pow(x, n)
Implement pow(x,n).
实现任意次方函数,注意:
1 n可以为正和负
2 x可以为正和负
下面使用二分法求解,不过因为两个的子解是一样的,所以可以只求一边解就可以了,这就是最典型的减治法了。
下面给出二分,三分,五分的求解程序:
double pow(double x, int n) {
if (n == 0 || x == 1) return 1;
if (x == 0) return 0;
if (n < 0) x = 1/x;
int a = abs(n);
if (a == 1) return x;
double t = pow(x, a/2);
if (a%2 == 1)
return x*t*t;
return t*t;
}
double pow3(double x, int n)
{
if (n == 0 || x == 1) return 1;
if (x == 0) return 0;
if (n < 0) x = 1/x;
int a = abs(n);
if (a == 1) return x;
double t = pow3(x, a/3);
double r = t*t*t;
if (a%3 == 0) return r;
if (a%3 == 1) return x*r;
return x*x*r;
}
double pow5(double x, int n)
{
if (n == 0 || x == 1) return 1;
if (x == 0) return 0;
if (n < 0) x = 1/x;
int a = abs(n);
if (a == 1) return x;
//到了5不加这句会处理不了-1的特殊情况,出现答案错误。
if (x == -1 && n%2 == 0) return 1;
else if (x == -1) return -1;
double t = pow5(x, a/5);
double r = t*t*t*t*t;
if (a%5 == 0) return r;
if (a%5 == 1) return x*r;
if (a%5 == 2) return x*x*r;
if (a%5 == 3) return x*x*x*r;
return x*x*x*x*r;
}
下面是不用递归利用某些特性求解的,看下面注解:
http://discuss.leetcode.com/questions/228/powx-n
/*
Consider the binary representation of n. For example, if it is "10001011", then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don't want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1 << i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<<i)). The loop executes for a maximum of log(n) times.
*/
double pow2(double x, int n) {
unsigned m = abs((double)n);//这里不要用int,否则会溢出。
double ret = 1;
for ( ; m; x *= x, m >>= 1) {
if (m & 1) { //m&1测试末位是否为1,是1就加上x,不是就不加。x是跟着移位不断平方
ret *= x;
}
}
return (n < 0) ? (1.0 / ret) : (ret);
}