calculate fibonaci in csharp

Here are two ways to calculate the Fibonacci sequence in C#:

  1. Using recursion:
main.cs
public static int FibonacciRecursion(int n)
{
    if (n <= 1)
    {
        return n;
    }
    else
    {
        return FibonacciRecursion(n - 1) + FibonacciRecursion(n - 2);
    }
}
185 chars
12 lines

This method uses recursive calls to calculate the Fibonacci number of n. It's simple to understand, but it can be very slow for large values of n.

  1. Using dynamic programming:
main.cs
public static int FibonacciDynamicProgramming(int n)
{
    int[] fib = new int[n+1];
    fib[0] = 0;
    fib[1] = 1;

    for (int i = 2; i <= n; i++)
    {
        fib[i] = fib[i - 1] + fib[i - 2];
    }

    return fib[n];
}
227 chars
14 lines

This method uses dynamic programming to calculate the Fibonacci number of n. It's much faster than the recursive method for large values of n. It uses an array to store previously calculated Fibonacci numbers, so that it doesn't have to recalculate them.

gistlibby LogSnag