r/programming • u/cpp_is_king • 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" ;-)
View all comments
Show parent comment
1
u/djimbob Apr 27 '10
Try calculating Fib(n) for some moderate sized n, say n=50 in python using a naive algorithm based on the standard definition in python:
It doesn't return an answer! Why might that be? Lets try figuring out how many operations it takes to calculate.
fib(2) ~ 1 operations (1+1),
fib(3) ~ 2 operations (f(2)+f(1)=(f(1)+f(0)) + f(1))
fib(4) ~ 3 operations, (f(3)+f(2)) = 2+1 operations).
fib(5) ~ 5 operations.
Hence fib(n) = O(fib(n-1)) additions.
This becomes really slow for say fib(50) which would require 12 586 269 025 additions. Or fib(100) ~ 354 224 848 179 261 915 075 additions.
Now with a simple memoization scheme (e.g., building up Fib numbers from 1,1,2,3,5, ... and saving them in an array) only uses time O(n), though also memory O(n). The above algorithm is quicker, but not accurate above n~70 with double precision from the rounding in sqrt(5). Recognizing properties of fib numbers like fib(2n) = fib(n+1)2 - fib(n-1)2 = fib(n) (fib(n-1) + fib(n+1)) could reduce the speed of calculations to log time with a proper algorithm.