【发布时间】: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;
}
【问题讨论】:
-
你的问题是什么,解释一下你的代码有什么问题。