【问题标题】:Power with divide & conquer algorithm分治算法的力量
【发布时间】:2014-10-28 10:43:19
【问题描述】:

我想找出计算 X^46 时,使用最佳 D&C 方法计算功率时发生了多少次乘法。

我认为这是使用分治法计算功率的最佳优化代码。

int power(int x, unsigned int y)
  {
     int temp;
     if( y == 0)
       return 1;
     temp = power(x, y/2);
     if (y%2 == 0)
       return temp*temp;
     else
       return x*temp*temp;
  }

在一篇为在 D&C 中使用最佳 Power 代码计算 X^46 所写的注释中,我们需要 8 次乘法,但在我的代码中有 10 次。有人纠正我吗?

编辑:

最后的代码是:

  int power(int x, unsigned int y)
  {
     int temp;
     if( y == 0)
       return 1;
     if( y ==1)
        return x;
     temp = power(x, y/2);
     if (y%2 == 0)
       return temp*temp;
     else
       return x*temp*temp;
  }

【问题讨论】:

  • 8 是从哪里来的?
  • 我认为你深入。为什么需要一直持续到 y==0?当 y==1 或 2 时停止。它可以节省一些乘法。顺便说一句,如果您知道效率,请改用y&0x1==0
  • @OliCharlesworth 重复平方,32+8+4+2=46
  • @HuStmpHrrr 一个体面的编译器会为你做这样的替换。
  • 顺便说一句。我不认为这算作分而治之,只是基本的递归。

标签: algorithm recursion data-structures divide-and-conquer


【解决方案1】:

您遗漏了

的优化基本情况
 if (y==1)
     return x

而是需要额​​外的乘法

 temp = power(x, 0)
 return x * temp * temp

额外的一对乘法来自不必要的最终递归调用。

【讨论】:

  • 亲爱的 Chepener,您能解释一下吗?
  • y==1 时,您可以立即返回x,因为x^1 == x 对于所有x。你不需要先递归计算x^0,然后返回x * 1 * 1
  • 能否请您更改我的代码并添加到您的答案中?
  • 您只需在函数中添加另一个基本案例。
【解决方案2】:

由于在y==1 时没有提前退出,所以你有多余的乘法。

y==1时,执行最后一行:

return x*temp*temp;

简化为:

return x*1*1;

y==1 添加一个特殊情况将消除额外的 2 个乘法。

【讨论】:

    【解决方案3】:
    int power(int x, unsigned int y)
      {
         int temp;
         if( y ==1)
            return x;
    
         if (y%2 == 0){
          temp = power(x, y/2);
           return temp*temp;
         }
         else{
           temp = power(x, (y-1)/2);
           return x*temp*temp;
         }
      }
    

    【讨论】:

      【解决方案4】:

      使用分而治之策略的最佳方法。完成执行需要 O(log N) 时间。它也适用于负指数。

      我在 C++ 中这样做:

      #include <iostream>
      using namespace std;
      
      float power(int a, int b)
      {
          if (b == 0)
          {
              return 1;
          }
          else
          {
              float temp = power(a, b / 2);
              if (b > 0)
              {
                  if (b % 2 == 0)
                  {
                      return temp * temp;
                  }
                  else
                  {
                      return a * temp * temp;
                  }
              }
              else
              {
                  return 1/power(a,-b);
              }
          }
      }
      int main()
      {       int a , b ;
              cout<<"Enter a Number:";cin>>a; cout<<"Enter its exponential:";cin>>b;
              cout << power(a, b);
      }
      

      输出:

      Output will be as follow

      【讨论】:

        猜你喜欢
        • 2013-02-12
        • 2021-05-06
        • 2013-02-02
        • 2020-07-17
        • 1970-01-01
        • 2012-10-28
        • 2017-04-07
        • 1970-01-01
        • 2010-12-07
        相关资源
        最近更新 更多