问题
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) ?
回答1:
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!
来源:https://stackoverflow.com/questions/22123221/iterative-logarithmic-exponentiation