Parallel Fibonacci Number Calculator

后端 未结 4 1548
南旧
南旧 2020-12-22 01:25

I\'m using Task Parallel Library (TPL ) for calculating Fibonacci number. Program is given below:

        public static int Fib(int n)
        {
                     


        
4条回答
  •  误落风尘
    2020-12-22 02:04

    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.

提交回复
热议问题