How to Code a Recursive Fibonacci Sequence

A Fibonacci Sequence is a sequence of numbers in which the first and second numbers in the sequence are 0 and 1 respectively, and additional numbers in the sequence are calculated by adding the previous two.

The first few numbers in the Fibonacci Sequence look like this:
0, 1, 1, 2, 3, 5, 8, 13, 21...

Often in technical interviews a person will be asked to “create a function that returns the nth value in a Fibonacci Sequence“. A recursive algorithm can solve this problem in a few simple steps as described below.

1. The first and second numbers in the sequence will always be 0 and 1 respectively. In this example we are assuming that n=0 represents the first number in the series. If 0 or 1 is passed to our function, then no calculation is needed. Simply return the value of n.

2. If n is greater than 1, recursively call function(n-1) + function(n-2).

While this algorithm is clean and simple, it has a relatively expensive time complexity, which in the worst case is approximately exponential. There are a variety of other simple but more efficient algorithms that can be used to solve this problem as well.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">