x
2
=
(
x
∗
x
)
→
x
4
=
(
x
2
)
∗
(
x
2
)
→
x
8
=
(
x
4
)
∗
(
x
4
)
∗
x
→
x
16
=
x
8
∗
x
8
→
x
32
=
x
16
∗
x
16
→
x
64
=
x
32
∗
x
32
x^2 = (x*x)\to x^4 = (x^2)*(x^2) \to x^8 = (x^4)*(x^4)*x \to x^{16} = x^{8}*x^8 \to x^{32} = x^{16}*x^{16}\to x^{64} = x^{32}*x^{32}
x2=(x∗x)→x4=(x2)∗(x2)→x8=(x4)∗(x4)∗x→x16=x8∗x8→x32=x16∗x16→x64=x32∗x32,6次操作
x
2
=
x
∗
x
→
x
4
=
(
x
2
∗
x
2
)
→
x
8
=
(
x
4
)
∗
(
x
4
)
→
x
10
=
(
x
2
)
∗
(
x
8
)
x^2=x*x\to x^4 = (x^2*x^2)\to x^8 = (x^4)*(x^4)\to x^{10}=(x^2)*(x^8)
x2=x∗x→x4=(x2∗x2)→x8=(x4)∗(x4)→x10=(x2)∗(x8),4次操作
可以看到,其实求幂的复杂度可以缩减为
o
(
l
o
g
2
n
)
o(log_2 n)
o(log2n),从复杂度上来看,可以推测快速幂就是对指数进行分治
classSolution{publicdoublemyPow(double x,int n){long d = n;double res =1, tmp = x;if(n<0) d=-d;while(d!=0){if((d&1)>0)
res = tmp*res;
tmp = tmp * tmp;
d>>=1;}return n>0?res:1.0/res;}}
递归,来自leetcode题解,不过这个空间复杂度高一些,因为递归函数占用了栈空间
classSolution{publicdoublequickMul(double x,long N){if(N ==0){return1.0;}double y =quickMul(x, N /2);return N %2==0? y * y : y * y * x;}publicdoublemyPow(double x,int n){long N = n;return N >=0?quickMul(x, N):1.0/quickMul(x,-N);}}