c++ - power() 的时间复杂度

标签 c++ c algorithm time-complexity

我实现了这个函数 power(),它接受两个参数 ab 并计算 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 : ablong long int 的范围内。
问题:如何降低算法的时间复杂度?

最佳答案

平方求幂。

enter image description here

非递归实现

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/

相关文章:

c++ - 计算单值子树

c - 指针结构的问题

c - pcap 结构 pcap_pkthdr len 与 caplen

c++ - 调用了 C 静态库,所有内容都包含在 extern "C"中,但它仍然无法正常工作

c++ - 为什么我们在 C++ 中没有 <cstdfloat>?

c++ - GNU G++ 编译器的 char* 常量值错误

c - 在 VC++ 2008 中运行程序时出现未处理的异常

algorithm - tribble 存活的概率是多少?

java - 创建另一个可迭代对象的可迭代组合

algorithm - 在 O(log n) 中找到中位数