The following code shows a recursive method that calculates Fibonacci numbers:
// Calculate the Fibonacci number recursively.private long RecursiveFibonacci(int number){ checked { // On 0 or 1, return 0 or 1. if (number <= 1) return number; // Fibonacci(N) = Fibonacci(N - 1) + Fibonacci(N - 2). return RecursiveFibonacci(number - 1) + RecursiveFibonacci(number - 2); }}
This method simply follows the recursive definition of Fibonacci numbers.
Fibonacci numbers grow very quickly (although not as quickly as the factorial function), so the program uses a checked block to protect itself from integer overflow errors.
Unfortunately, this method has a more pressing problem—it recalculates certain values a huge number of times. ...