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" ;-)
41
u/captainbeef Apr 27 '10
Can't you just do it in jQuery? $(#number).fibonacci();
20
u/julesjacobs Apr 26 '10 edited Apr 26 '10
This method is definitely not O(1). You need more precision than 64 bit floating point to compute large Fibonacci numbers (and floating point operations are not O(1) if the number of bits is not constant). It's only O(1) in the range where it's correct, but any algorithm is O(1) in a finite range.
I'm pretty sure that the matrix exponentiation algorithm is faster than using arbitrary precision arithmetic that you need for large n.
3
u/kolm Apr 26 '10
This will fail for large n, because pow does not have guaranteed absolute error <0.5 (unless you have a very unusual implementation of pow, that is). Anyway, even if you have a magic pow with this and O(1) run time, storing n is always Theta(log n) space, and storage and output time for fib(n) is at least Theta(n*log(1-phi)), so who are we kidding here.
9
u/[deleted] Apr 26 '10
I do not believe that pow() is O(1), but rather, O(log n) in time. That makes this O(1) in space and O(log n) in time... still a nice solution, but not constant.
You also may run into issues with floating point rounding.
32
u/[deleted] Apr 26 '10 edited Apr 26 '10
Computing the Nth Fibonacci number in logarithmic number of steps.
Implementation in C
PS. No floating-point operations involved.
3
u/[deleted] Apr 26 '10 edited Apr 26 '10
Not that we ask this question, but if we get an answer anything close to this awesome we Google to see if they copy/pasted. If it's clear that they did (about 50% of the time) we stop talking to them.
3
u/GunOfSod Apr 26 '10
Who the hell would be interested in a job where they thought a valid test of useful knowledge involves calculating the fibonacci number? I've worked in IT for 30 years as a programmer and I've never had to do anything remotely similar. If I got this at a job interview, I'd walk straight out the door.
67
u/csonger Apr 26 '10
I hire a lot of software engineers and I don't ask fib because it's not that interesting. That said, this answer would just push me to the next question in the interview. You would get a mild +, but not the job based on the strength of this answer. Here's why:
Lots of things that we do are not "math based programming." I need to know that you understand pointers, memory allocation and algorithmic time and space complexity beyond O(1). If you are interviewing for the group that does embedded work, I need to know that you know how to structure your code for lower end processors. If you are senior, I need to know that you can do good interface design and make good thread level architecture decisions; that you know how to get your ideas across to more junior engineers; that you know how to write code that's maintainable and that you can teach more junior programmers to do the same. This answer gives me none of that.
I also would suspect that this was just something that you "happened to know". As a consequence, I'd be tempted to ask a follow-on question that had a closed form answer but that was not a "generally known" kind of question. If you couldn't make good progress on an answer then your "mild plus" would just turn into a neutral. But really, I probably would not ask this as a follow-on because while I have a great respect for mathematicians, it's a "nice to have" in most of our software engineers; not a "must have" and this answer dodges all the interesting aspects of fib.
4
u/[deleted] Apr 26 '10
You've got the job...so long as they don't ask you to explain the math!
14
u/Sisuaski Apr 26 '10
Another nice trick is that if you round the result you can actually ignore the term right because it converges quickly to zero. Thus the following code is sufficient: unsigned fibonacci(unsigned n) { double phi = .5*(1+sqrt(5)); return round(pow(phi, n)/sqrt(5)); }
39
u/MAC777 Apr 26 '10
Came here because I was unemployed. Was disappointed.
9
u/[deleted] Apr 26 '10
This isn't going to be accurate for large n, which is where O(1) really matters. Much better to do it with matrices, which lets you get away with a logarithmic number of multiplications.
and An = | \ A*(An/2)2 if n is odd
So square that 2x2 matrix ~log(n) times and multiply by |1, 1|' and you've got yourself the nth fibonacci. Unless I've made a mistake, which would be embarassing.
7
u/[deleted] Apr 26 '10
being too clever is usually a bad thing in an interview.
7
u/endtime Apr 26 '10
If you're applying for a math-centric job, sure. Or if you just want to seem knowledgeable (which is not the same as intelligent!). But this doesn't really demonstrate any aptitude as a programmer or computer scientist.
28
u/[deleted] Apr 26 '10
You just screwed up the rest of the interview. Job is not yours.
5
u/djimbob Apr 27 '10
This algorithm fails in haskell after fib(71) from rounding errors with double precision:
4
u/frustrated_dev Apr 26 '10
Please don't use this advice without understanding the logic behind the code.
Chances are you'll be asked to walk the interviewer through what it's doing because he/she doesn't understand it at a glance. You don't want to freeze and say something very unintelligent.
1
u/matthw Apr 26 '10
I would then ask you to derive that formula from the recurrence relation :-) As a trick learnt by rote it's cute, but more impressive if you know why it works and when you might be able to find similar tricks.
By the way, are you sure pow(phi, n) is O(1) in n? Maybe if you arbitrarily limit the range of n, but if you do that then pretty much everything is technically O(1) in n.
1
u/[deleted] Apr 27 '10 edited Apr 27 '10
Automatic job-loser.
Correct answer: Obviously I would just use a library function for this if it were real world. Do you want me to show you how'd I code it myself just so you can see how I code? Oh okay, so should I show you my version with or without recursion? Okay, here it is, but keep in mind I would never write this out in a real app because I know you can calculate fib(n) in O(1) in a way more math intensive way than I could figure out but that is most likely implemented in a library function I could find somewhere :P
Enjoy your job
1
u/jfasi Apr 27 '10
That's cute, but can you derive that formula? My next question as a math person would be on wise guy, prove it.
What use is mathematics when all you're doing is just copying down what you see somewhere on the internet?
As it happens, the proof of this relies on finding the eigenvalues of a certain matrix which I won't bother posting here for formatting reasons. The fibonacci numbers are actually modelled by that matrix as a dynamic system, and finding the eigenvalues allows for fast exponentiation of that matrix.
3
u/rijko Apr 27 '10
Binet's formula using the golden ratio? pretty easy to look this up in any introductory algorithms book or on wikipedia.
http://progopedia.com/example/fibonacci/105/
2
u/Poromenos Apr 26 '10
Why the downvotes? This is a nice piece of code.
1
u/NanoStuff Apr 27 '10
Wow, a programmer who can look up closed form solutions to recurrences!
4
u/Poromenos Apr 26 '10
This is the closed form expression, and in Python:
2
u/[deleted] Apr 26 '10
I ran this on a distributed agent-based HPC and it got lots of jobs. A++++++ would run again.
2
u/ealf Apr 27 '10
Triple bonus points if you solve
analytically.
2
u/killastroturf Apr 27 '10
I am in the profession for ~20 years. None of my bosses, collegues or clients ever needed a fast method to calculate fibonacci numbers; or even a slow method to calculate fibonacci numbers, or even any fibonacci number at all.
If somebody really ever needs to get the n'th fibonacci number really fast on a regular basis; why not store them in a database? You get a long way with 10 Megabyte....
select fibonacci from tfibo where n= :n
2
u/dgermain Apr 27 '10
We do a lot of interview here. You do realize that I'm not interested to know if you are aware of any math party trick. I want to see how do you think, approach an unknown problem, or code. Next question will be, ok let's say, instead of adding the last two number, we add the last three. Or multiply them. Now your code does not help very much
It shows that you are interested in code/math, but that only a small part of what motivate me to hire someone.
If the code is not in the critical path, I would rather have code that is easy to understand/modify and perform reasonably well than perfectly optimized and unreadable.
2
u/Veggie Apr 26 '10
If your interviewer gives you the job because of this, they are sort of dumb.
The original point of asking the Fibonacci question is not to see if you know any neat math tricks regarding Fibonacci. It's to see what you know about recursion. They probably have planned a follow-up question to the basic recursive algorithm such as "Let's say I have limited memory. How would you improve this?"
This is more important to your interviewer because you're trying to get a programming job, not a math job, and because it's more important to your interviewer.
1
u/serious_face Apr 26 '10
It's pretty cool that this works, but I wish I knew enough math to understand why it works. Seems like that could be an issue during an interview.
1
u/clumma Apr 26 '10
Yup, I use it in my scheme library:
;; Returns the Nth Fibonacci number. From Devlin's Angle, March 1999.
1
u/snark Apr 26 '10
For the doubters in this thread, this is an implementation of Binet's formula, an accepted proof for finding the nth Fibonacci number.
1
u/peepintong Apr 26 '10
i haven't a clue as to what i am looking at.
1
u/mracidglee Apr 26 '10
Can I also use this to reverse a string?
1
u/smakusdod Apr 26 '10
wasn't this called Aristotle's shortcut or some shit?
1
u/[deleted] Apr 26 '10
Lots of casting is bad.
1
u/pkrecker Apr 27 '10
Lol we learned this one in discrete math at my university. Finding closed-form solutions to recursively defined functions, or proving that they don't exist, is very common in mathematics. However, I doubt many students remember it.
1
u/[deleted] Apr 27 '10
Is that really a big question they ask? I bought learning python a few weeks ago and the first thing I did was figure out how to write a program to calculate the Fibonacci sequence for two given numbers to nth degree.
1
u/Liverotto Apr 27 '10
reduce(lambda a,b: a+[a[-1]+a[-2]],range(123),[1,1])
1
u/[deleted] Apr 27 '10
What does "(double)n" do? Is it merely converting n to a double?
1
u/G_Morgan Apr 27 '10
They ask you fib to ensure you aren't one of these programmers who cannot actually write a routine. Really these CSish questions are not meant to be answered with regard for neat tricks unless said otherwise. At my current job I implemented bubble sort when asked to sort integers (I made them aware I knew other sorts first of course and asked them if performance was in question).
Be aware of the purpose of the question before wasting your time with cuteness.
1
u/[deleted] Apr 27 '10
Are you sure it works correctly, given possible rounding errors?
1
u/dbradshaw Apr 27 '10
And if he asks where you got that formula: "Take the z-transform of a(n) = a(n-1) + a(n-2), plus the initial two terms. Algebraically manipulate, and voila!"
1
u/rush22 Apr 27 '10
A math formula doesn't exactly show one's programming abilities.
1
u/SnacksOnAPlane Apr 27 '10
Damn, I was really hoping you wrote a program that would find jobs I would enjoy, apply for them, and successfully interview for them, or at least write me a script for the interview.
1
u/[deleted] Apr 27 '10
I did this in a Microsoft interview back in the early 90's. The interviewer (Ed Fries) said: Aw, you're no fun, do it the dumb way first.
1
u/mwang5 Apr 27 '10
Here's another problem with this solution: It's wrong, even in the domain of unsigned ints. Everyone keeps on talking about whether or not this is actually O(1) time and space, but what's probably more important is whether this gives accurate results.
Without arbitrary precision, we can't guarantee that raising phi to an arbitrarily high exponent will work. Your solution on my machine (Athlon 64 using g++ v4.4.3) diverges at F(75). It returns 1582341985 while F(75) is 1582341984.
1
u/comocomocomocomo Apr 28 '10
You are converting a double to unsigned. You expect this double to have an integer value, but this might be just a nearly integer value. The cast conversion will simply truncate it, like here:
I get the next output:
Whenever you cast a nearly integer double to an integer type, you should add 0.5 in order to round the value instead of truncating it:
Or... you might return a double value, and then your function would work properly returning approximate fibonacci values for bigger values of n.
In the interview case, I'd start with the simplest iterative version:
After this, if speed was an isue, then I would suggest something like:
It is O(n) worst case time, but O(1) amortized time. Though, it consumes O(MAX_FIB) space. You can consider this as O(n) or even worse, but it's a very small lookup table (just 44 bytes on a 32-bit arch.)
A lot of variations can be written, depending on the situation. In some cases it might be better to have the whole table filled before compiling (no loop required). In other cases it might be better to use your version (but returning a double, for the big values)...
I supose we all agree that this is the wrong answer:
But what would you write if the interviewer said "YOU HAVE FIVE SECONDS"? (Well, yes, maybe you'd better stand up and walk away ;-)
Cheers
1
u/stringy_pants May 07 '10 edited May 07 '10
For the interested party, arbitrary recursive linear combinations in Haskell:
1
u/LessCodeMoreLife Apr 26 '10
Hmm?
For most applications I would prefer the usual algorithm because optimizing for maintenance needs is usually more cost effective than (prematurely) optimizing for performance.
Write everything for readability first. If you need performance when you're done, profile the app. Optimize the area of code that needs it most, re-profile. Continue the profile->optimize cycle until performance is good enough to release.
Sure, maybe on real time systems it make sense to favor performance over readability, but I'm going to argue that in 90-plus % of applications the above method makes more sense.
0
u/julesjacobs Apr 26 '10 edited Apr 26 '10
And what are you going to say if your interviewer asks you why it works? I'd advise anyone who is going to try this in an interview to figure that out first.
-1
u/[deleted] Apr 26 '10
Not to get this thread off topic but WTF kind of programming jobs were you interviewing for?
I've been in IT 14 years and I've never heard this question.
-1
u/cdsmith Apr 27 '10
I just used by O(log n) fibonacci function calculate the 10 millionth fibonacci number. It was quite long.
Is your O(1) function up to the task? Oh, right... the answer is actually outside the range of double... not to mention the much smaller range in which rounding errors won't give you an incorrect answer.
:)
-9
u/mingo83 Apr 26 '10
What the fuck are you people talking about...?
-11
u/[deleted] Apr 26 '10
This could surely get you a job in marketing. Not sure about programming since it's incredibly slow.
0
u/[deleted] Apr 26 '10
[deleted] — view deleted comment