1

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;
    }

1 Answers1

0

You're very close. It appears to me that you have the correct method in both pieces of code, but slipped up slightly in the loop body of the iterative version:

x = x * x;

should be:

result = result.multiply(result)

because you want to square your running total, not the input variable. Test that out on a few small inputs to see if it works correctly!

EDIT: still didn't work, found a solution here: Iterative logarithmic exponentiation

soothsooth
  • 173
  • 8
  • I have tried what you said but it seems that I'm not doing the last two multiplications. With the recursive one equals to 16 and the iterative one equals to 4. Both cases trying 2^4. – Joan Vilella Candia Dec 05 '20 at 12:33
  • Perhaps I was wrong. Solution here: https://stackoverflow.com/questions/22123221/iterative-logarithmic-exponentiation – soothsooth Dec 06 '20 at 13:44