【问题标题】:Pow function from recursive to iterativePow 函数从递归到迭代
【发布时间】:2021-03-17 06:55:24
【问题描述】:

我的任务是执行复杂度为 O(logn) 的递归 pow 函数,然后以迭代方式执行相同的算法。第一个我认为我拥有它,但是,我在以迭代方式做完全相同的事情时遇到了麻烦。我有一个 O(logn) 但不是同一个。

public static BigInteger powV2(int x, int y) {
        if (y == 0) {
            return BigInteger.ONE;
        }
        BigInteger powerOfHalfX = powV2(x, y / 2);

        if (y % 2 == 0) {
            return powerOfHalfX.multiply(powerOfHalfX);

        } else {
            return BigInteger.valueOf(x).multiply(powerOfHalfX).multiply(powerOfHalfX);

            //x * powerOfHalfX * powerOfHalfX;
        }
    }

这是迭代的:

public static BigInteger iterativePowV2(int x, int y) {
        BigInteger result = BigInteger.ONE;

        while (y > 0) {
            if (y % 2 == 1) {
                result = result.multiply(BigInteger.valueOf(x));
            }

            y = y >> 1; //y = y/2
            x = x * x; //
        }

        return result;
    }

【问题讨论】:

  • 你的问题是什么,解释一下你的代码有什么问题。

标签: java recursion iteration


【解决方案1】:

你很亲密。在我看来,您在两段代码中都有正确的方法,但在迭代版本的循环体中略有下滑:

x = x * x;

应该是:

result = result.multiply(result)

因为您想要对运行总数进行平方,而不是输入变量。在几个小的输入上测试它是否正常工作!

编辑:仍然没有工作,在这里找到了解决方案:Iterative logarithmic exponentiation

【讨论】:

  • 我已经尝试过你所说的,但似乎我没有做最后两次乘法。递归的等于 16,迭代的等于 4。两种情况都尝试 2^4。
  • 也许我错了。解决方案:stackoverflow.com/questions/22123221/…
猜你喜欢
  • 2016-03-01
  • 2021-12-31
  • 2019-06-20
  • 2013-12-31
  • 2019-04-03
  • 2011-05-05
  • 1970-01-01
相关资源
最近更新 更多