Lab 14: Recursion and Dynamic Programming
Fibonacci numbers are a sequence beginning with 1, followed by another 1, and then each number after is the sum of the two previous numbers. Refer to Wikipedia for the definition. Use the first "classical" version of the sequence, without a leading 0. Write a function that calculates the nth fibonacci numbers, fib(n). fib(1) will return 1, fib(2) will return 1, fib(3) will return 2, fib(4) will return 3, fib(5) will return 5, etc.
Use recursion to calculate each number. Note that this requires two recursive calls, one for fib(n-1) and one for fib(n-2). Don't forget the base case if n less than 3.
Once your function works, use a global variable to track the number of recursive calls that are made. Add one to this variable every time your fib function is called, and print out the value of this variable when calculating the 25th fibonacci number. This indicates the total number of stack frames that were created for fib (the maximum in existance at any point will be about 24).
Finally, use a technique called Dynamic Programming to solve this problem in less time. Increase n until your program runs kind of slow (this will depend on the computer you are using). Then, set up a global dictionary, and store any fibonacci numbers generated. Before returning a value from your fib function, save it in the dictionary using n for a key and the fibonacci number for a value. Then, at the beginning of your fib function, check to see if fibonacci number n is already in the dictionary (if n in my_dictionary: ). If it is, just return the value from the dictionary instead of calculating it. Then check for both reduced runtime and reduced number of stack frames created.