Deb*_*jan 18 c c++ algorithm time-complexity
我实现了这个功能,power()这需要两个参数a和b并计算b.
typedef long long int LL;
LL power(int a,int b)
{
int i = 1;
LL pow = 1;
for( ; i <= b ; ++i )
pow *= a;
return pow;
}
Run Code Online (Sandbox Code Playgroud)
鉴于:a b属于范围long long int.
问题:如何降低算法的时间复杂度?
Pra*_*rav 33
Squaring的指数.

非递归实现
LL power(int a, int b)
{
LL pow = 1;
while ( b )
{
if ( b & 1 )
{
pow = pow * a;
--b;
}
a = a*a;
b = b/2;
}
return pow;
}
Run Code Online (Sandbox Code Playgroud)
该算法需要log 2 b squarings并且最多log 2 b乘法.
运行时间为O(log b)