It is totaly wrong to write Fibonacci with recursive methods!!
It is an old famous example for how a good/bad Algorythm affect any project
if you write Fibonatcci recursive, for calculating 120
you need 36 year toget the result!!!!!!
public static int Fibonacci(int x)
{ // bad fibonacci recursive code
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
in dot net 4.0 there is a new type name BigInteger and you can use it to make a better function
using System;
using System.Collections.Generic;
using System.Numerics; //needs a ref. to this assembly
namespace Fibonaci
{
public class CFibonacci
{
public static int Fibonacci(int x)
{
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
public static IEnumerable<BigInteger> BigFib(Int64 toNumber)
{
BigInteger previous = 0;
BigInteger current = 1;
for (Int64 y = 1; y <= toNumber; y++)
{
var auxiliar = current;
current += previous;
previous = auxiliar;
yield return current;
}
}
}
}
and you can use it like
using System;
using System.Linq;
namespace Fibonaci
{
class Program
{
static void Main()
{
foreach (var i in CFibonacci.BigFib(10))
{
Console.WriteLine("{0}", i);
}
var num = 12000;
var fib = CFibonacci.BigFib(num).Last();
Console.WriteLine("fib({0})={1}", num, fib);
Console.WriteLine("Press a key...");
Console.ReadKey();
}
}
}
and in this case you can calculate 12000
less than a second. so
Using Recursive methos is not always a good idea
Above code imported from Vahid Nasiri blog whiche wrote in Persian