Chrishan - Chris, Shannon, Jasmine, & Kai

Friday, September 21, 2007

Bad Programming Humor

We are currently looking to hire another php programmer at work and today we where going though and finalizing interview questions. My boss was saying it would be fun to have a silly question at the end to hint at the fact that we are a fun group to work with. His idea was a question like "Are you more a spoon or a fork".

Both Dan (coworker) and I agreed his question wasn't in our taste. I mentioned that it would be fun to do some kind of code joke. For example have them evaluate something with a hidden joke in it. Dan mentioned the fibonacci sequence.

Not sure if that really comes out funny or not, but it stuck and this evening I couldn't help myself. I had to create an example. My first thought being that the fibonacci sequence is the perfect example for using recursion. Of course I wanted to make it in the least amount of lines as possible and came up with this

function fib($n){return ($n < 3)?1:(fib($n-1) + fib($n-2));}
for($i=1;$i <= 20;$i++){echo " ".fib($i);}

It worked out great but two things bothered me, first was the fact that it was two lines (well i cheated a bit) and second that recursion is not the most efficient solution when we want to go out a ways "n" wise. For example n = 50, would start taking a second or two to process.

So I spent a while researching before I came across Binet's formula

an = [ Phin - (phi)n ]/Sqrt[5])

This uses the golden mean (Phi) to calculate the Nth place in the sequence.

With this new formula in hand I was able to create one line of code (still cheating), to create a fib. sequence. This example was a lot more efficient than the previous recursive one.

for($i=1;$i <= 20;$i++){echo " ".(( pow(((1+sqrt(5)) / 2),$i) - pow(((1-sqrt(5)) / 2),$i) ) / sqrt(5));}

Okay, I know this post is really only geared towards two readers on my blog. Feel free to surprise me with a comment, how many of you got the code or understand the math?

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home