I\'m using Task Parallel Library (TPL ) for calculating Fibonacci number. Program is given below:
public static int Fib(int n)
{
Your program is very inneficient, because same calculation are repeated (Fib(n-1) actually recalculate the Fib number for all numbers < n -2, which has be done yet).
You should try this :
class Program
{
static void Main(string[] args)
{
var sw = new Stopwatch();
sw.Start();
foreach (var nbr in Fibo().Take(5000))
{
Console.Write(nbr.ToString() + " ");
}
sw.Stop();
Console.WriteLine();
Console.WriteLine("Ellapsed : " + sw.Elapsed.ToString());
Console.ReadLine();
}
static IEnumerable Fibo()
{
long a = 0;
long b = 1;
long t;
while (true)
{
t = a + b;
yield return t;
a = b;
b = t;
}
}
}
44th find in 5ms.
The slowest part of the code is the Console.Write in the loop.