Jul 17, 2012

Java coding question on the popular Fibonacci sequence

The Fibonacci sequence is 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, and 89 on to infinity is popular with the interviewers. The sequence has a series of interesting properties. The sum of any two consecutive numbers equals the next highest number. After the first four numbers, the ratio of any number to its next highest number approaches 0.618. The ratio of alternate numbers approach .382. These ratios are often simplified to the key Fibonacci levels 38%, 50%, and 62% and used in stock trading analysis, growth in living things like reproduction of rabbits, arrangement of leaves in a plant, scales of pineapples, etc. So, why is this asked in programming interview questions? This is to see if you can think logically and write code. Here are a few questions on this Fibonacci sequence.

Where the zeroth number being 0, first number being 1, second number being 1 (i.e. 0+1), third number being 2 (i.e. 1+1), fourth number being 3 (i.e. 1+2) and so on till the 17th number being 1597 (i.e 610 + 987).

Q. Can you write a function to determine the nth Fibonacci number?A. This can be achieved with recursion or iteration. You can learn more about recursion at iteration Vs recursion. If you provide an iterative solution then there will be follow up question to write recursive solution and vice versa.