我实现了这个函数 power()
,它接受两个参数 a
和 b
并计算 ab。
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;
}
Given : ab 在 long long int
的范围内。
问题:如何降低算法的时间复杂度?
最佳答案
平方求幂。
非递归实现
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;
}
该算法需要 log2b 次平方和最多 log2b 次乘法。
运行时间为O(log b)
关于c++ - power() 的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5231096/