Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiency of my Java power method?

So I went into a job interview and they asked me to write up a quick math power method on a white board and this is what I put up there

public static double pow(double base, double power) {
    double result = 1.0;
    for(double x = 0; x < power; x++) {
        result = result * base;
    }

    return result;
}

This worked and they were satisfied with it, but then proceeded to ask me how I could make it more efficient and i had no response. So my question is, can you get more efficient than this or was that just a question to make me sweat a little bit? I'm thinking that there could be some direct bit shifting solution but I'm not exactly sure, I think that would only apply for powers of 2? Any ideas?

*EDIT Sorry I forgot to mention that that the method signature was given to me (the doubles as inputs) and i was told i could not use any built-in math libraries.

like image 795
Raymond Holguin Avatar asked Apr 23 '13 23:04

Raymond Holguin


1 Answers

http://en.wikipedia.org/wiki/Exponentiation_by_squaring The "basic method" is O(log n), as opposed to this O(n) algorithm. (Guava has a non-recursive implementation.)

Also, your power parameter should almost certainly be an int. (If you really want to implement an algorithm to raise numbers to non-integer powers, you're going to need a lot more math.)

like image 107
Louis Wasserman Avatar answered Sep 20 '22 00:09

Louis Wasserman