Calculating Fibonacci Numbers
Explore how to calculate Fibonacci numbers by understanding the classic recursive approach and its inefficiencies. Learn to analyze time complexity through recurrence relations, identify redundant calculations, and apply memoization to optimize the algorithm for better performance in C#.
Classic recursive implementation of the Fibonacci series
Before we dive into what dynamic programming is, let’s have a look at a classic programming problem: the Fibonacci series. You’ve probably already seen it, but let’s start with a quick refresher. The Fibonacci series is a series of numbers in which each number is the sum of the preceding two numbers. The first two numbers are 0 and 1. So, it looks like 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
Here is a C# method that returns the Fibonacci number.
This is the Fibonacci golden spiral. The width of each square represents a Fibonacci number.
Time complexity with recurrence relations
To calculate the time complexity of the code, we can solve a recurrence relation,
represents the Fib method. and represent the recursive calls to Fib(n-1) Fib(n-2), whereas the represents the basic operations in the code. Namely, the comparison on line 12 and the two subtractions and one addition on line 17. Lastly, and ...