Should approach fastPowering this way?

未关闭
#299 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
42/100
Issue 类型
重构
描述清晰度
基本清楚
活跃度
停滞
技术栈
javascript
领域
tooling

调研方向

Read fastPowering.js and compare its odd and even branches with the proposed shared multiplier calculation. Verify that the refactor preserves results for zero, even, and odd powers; done means the approach is accepted and the issue is closed.

由索引模型根据 Issue 内容生成。

描述

While learning about Fast Powering Algorithm, I notice that a minor tweak can be made to the fastPowering.js file.

In both of the cases whether the power is odd or event, calculated multiplier will be the same. So, we can calculate multiplier before the if clause and return the multiplication based on the nature of power.

export default function fastPowering(base, power) {
  if (power === 0) {
    // Anything that is raised to the power of zero is 1.
    return 1;
  }

  // multiplier will be same whether power is even or odd
  const multiplier = fastPowering(base, Math.floor(power / 2)); 
  if (power % 2 === 0) {
    // If the power is even...
    // we may recursively redefine the result via twice smaller powers:
    // x^8 = x^4 * x^4.
    return multiplier * multiplier;
  }

  // If the power is odd...
  // we may recursively redefine the result via twice smaller powers:
  // x^9 = x^4 * x^4 * x.
  return multiplier * multiplier * base;
}

@trekhleb Let me know your thoughts. And if you're okay with this implementation I can raise a PR.

主要语言
JavaScript
星标
197k
派生
31k
PR 合并指标
30 天内没有已合并 PR

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

trekhleb/javascript-algorithms 的其他 Issue

查看 trekhleb/javascript-algorithms 的全部 Issue

相似的 Issue

更多 JavaScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。