I have the task of doing a recursive pow function with complexity of O(logn) and then do the same algorithm in iterative way. The first one I think that I have it but, I'm having trouble in doing the exact same on a iterative way. I have one that is O(logn) but it's not the same one.
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;
}
}
this is the iterative one:
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;
}