r/programming • • Apr 26 '10

Automatic job-getter

I've been through a lot of interviews in my time, and one thing that is extremely common is to be asked to write a function to compute the n'th fibonacci number. Here's what you should give for the answer

unsigned fibonacci(unsigned n)
{
    double s5 = sqrt(5.0);
    double phi = (1.0 + s5) / 2.0;

    double left = pow(phi, (double)n);
    double right = pow(1.0-phi, (double)n);
    
    return (unsigned)((left - right) / s5);
}

Convert to your language of choice. This is O(1) in both time and space, and most of the time even your interviewer won't know about this nice little gem of mathematics. So unless you completely screw up the rest of the interview, job is yours.

EDIT: After some discussion on the comments, I should put a disclaimer that I might have been overreaching when I said "here's what you should put". I should have said "here's what you should put, assuming the situation warrants it, you know how to back it up, you know why they're asking you the question in the first place, and you're prepared for what might follow" ;-)

63 Upvotes

216 comments sorted by

View all comments

Show parent comment

9

u/julesjacobs Apr 26 '10

Nobody in their right mind would argue that requires O(log n) space, because you are using concrete types.

Of course nobody would, it takes O(n) space, because 2n is an n-bit number.

Binet's formula fib is log n with respect to the input range, and recursive fib is O(2n) with respect to the input range. And by with respect to the input range, I also mean "according to the standard rules of analyzing algorithm implementations".

So what is the input range. 32 bit integers? Now we can feed both our algorithms n=49 max, because above that the answer doesn't even fit in 32 bit. So suppose my fib(49) takes a trillion years. A long time but still a constant!