二分求幂—递归非递归两种方法

二分求幂是快速的求得a的b次方,时间复杂度为O(logn)

一般求a的b次方就是使用一个循环,每次乘以一个a:

res=1;
for(int i=0;i<b;++i)
{
res*=a;
}
return res;

时间复杂度为O(n)


递归的二分求幂算法为:

int power(int a,int b)
{
if(b==0)
return 1;
if(b%2==0)
return power(a*a,b/2);
return a*power(a*a,b/2);

}

非递归的二分求幂算法为:

int power(int a,int b)
{
int res=1;
while(b)
{
if(b%2==1)
res*=a;
b/=2;
a*=a;
}
return res;
}

猜你喜欢

转载自blog.csdn.net/ZHUJIANWEILI4/article/details/44728777