Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterative logarithmic exponentiation

I bombed an interview (phone screen with collabedit) recently. Here is the question: Write an interative O(lg n) algorithm for finding the power of x^y (x is a double, y>0 is an int).

I first did the recursive divide and conquer one and tried to convert it to iterative... and I couldn't :S Is there a method to convert recursion to iterative (it is easy for tail recursion, but how about recursive functions with two possible recursive calls which depend on conditions to decide which call will be invoked) ?

like image 357
user87219 Avatar asked Aug 01 '26 22:08

user87219


1 Answers

The typical way to unroll this uses the bitwise representation of b. Compute a1, a2, a4, a8, etc. and at each step determine whether or not to multiply it into the total. This is shown here:

double result = 1;
double multiplier = a;
for (double multiplier = a; b != 0; multiplier *= multiplier, b /= 2) {
    if (b % 2 == 1) {
       result *= multiplier;
    }
}

For example, to compute 35, we'd notice that 5 has binary representation 101, so we'd multiply in 31 and 34.

Hope this helps!

like image 100
templatetypedef Avatar answered Aug 04 '26 13:08

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!