今天看交大的数据结构书,看到了一个计算n次方的好算法,它的时间复杂度只有logN,
一般我们可能用循环,时间复杂度是O(n),当这个算法只有O(logN) 确切点说是O(6logN)
算法贴来...真高兴!
intpower(intx,intn)
{
intm=0;
m=n;
intt=1;
while(m>0)
{
m/=2;
t*=2;
}
m=n;
inty=1;
while(t>1)
{
t/=2;
y*=y;
if(m>=t)
{
y*=x;
m-=t;
}
}
returny;
}
{
intm=0;
m=n;
intt=1;
while(m>0)
{
m/=2;
t*=2;
}
m=n;
inty=1;
while(t>1)
{
t/=2;
y*=y;
if(m>=t)
{
y*=x;
m-=t;
}
}
returny;
}
原理
一般的对于 a (2x + b)= a2x * a b
所以就有
(b = 0时 ) : a 2x+ b = (ax)2 ;
(b = 1时):a 2x+ b = (a x)2 * a ;
对于 an ,先把 n的二进制表示写出,那么有
an = a (n1 n2 n3 n4 ..)(2) = …
从左到右就可以如下表(n = 15的时候 1111)
|
n的二进制位 |
1 |
1 |
1 |
1 |
|
累乘 |
a |
a2 * a = a3 |
(a3)2 *a= a7 |
(a7)2 * a = a15
|
就这样的.
628

被折叠的 条评论
为什么被折叠?



