Iterative logarithmic exponentiation

六眼飞鱼酱① 提交于 2021-02-08 02:01:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!