权力的时间复杂度()

Deb*_*jan 18 c c++ algorithm time-complexity

我实现了这个功能,power()这需要两个参数ab并计算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)



Eri*_*lle 5

通过平方求幂并不能在所有情况下给出最小乘法次数。寻找“加法链”、“布劳尔链”、“汉森链”和“肖尔茨猜想”。

  • 如果这个答案链接到阅读这些特定算法,它会更有用。 (3认同)