algorithm - 使用分而治之算法的力量

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

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

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

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 中使用最佳幂代码计算 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;
  }

最佳答案

您遗漏了

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

而是需要额​​外的乘法运算

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

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

关于algorithm - 使用分而治之算法的力量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25652665/

相关文章:

algorithm - 这个嵌套的三重 for 循环的复杂性是什么?

arrays - 查找特定元素上排序数组的范围索引

algorithm - 与学术伪代码一起使用的集合/向量/映射操作概述

c# - 没有递归或无限循环的 StackOverflowException?

java - 使用Java编码质询问题查找并格式化森林中树木视觉上美观的令人愉悦的图案

java - 当我尝试在 BST 中找到最接近 -1 的值时,为什么会得到错误的答案?

algorithm - 邀请人们参加聚会的最佳算法

php - 递归删除

c++ - C++14 中通用 lambda 函数的递归

c# - 从 Linq 中的列表中选择多个字段