求斐波那契数列第n位的几种实现方式及性能对比

    xiaoxiao2021-04-16  209

    在每一种编程语言里,斐波那契数列的计算方式都是一个经典的话题。它可能有很多种计算方式,例如:递归、迭代、数学公式。哪种算法最容易理解,哪种算法是性能最好的呢?

    这里给大家分享一下我对它的研究和总结:下面是几种常见的代码实现方式,以及各自的优缺点、性能对比。

    Iteration

    using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;public class Program{public static void Main(){var watch = new Stopwatch(); watch.Start();var r = Fibonacci().Take(40).Last(); watch.Stop(); Console.WriteLine($"计算结果:{r},耗时:{watch.Elapsed}"); Console.ReadLine(); }private static IEnumerable<int> Fibonacci(){int current = 1, next = 1;while (true) {yield return current; next = current + (current = next); } }}

    计算结果:102334155,耗时:00:00:00.0029930

    Recursion

    using System;using System.Diagnostics;public class Program{public static void Main(){var watch = new Stopwatch(); watch.Start(); Func<int, int> fib = null; fib = x => x < 2 ? x : fib(x - 1) + fib(x - 2);var r = fib(40); watch.Stop(); Console.WriteLine($"计算结果:{r},耗时:{watch.Elapsed}"); Console.ReadLine(); }}

    计算结果:102334155,耗时:00:00:00.7022325

    Tail Recursion

    using System;using System.Diagnostics;using System.Threading;public class Program{public static void Main(){var watch = new Stopwatch(); watch.Start(); Func<int, int, int, int> fib = null; fib = (n, a, b) => n == 0 ? a : fib(n - 1, b, a + b);var r = fib(40, 0, 1); watch.Stop(); Console.WriteLine($"计算结果:{r},耗时:{watch.Elapsed}"); Console.ReadLine(); }}

    计算结果:102334155,耗时:00:00:00.0001280


    这几种实现方式总结:

    迭代

    代码逻辑清晰,容易理解,性能中等。

    递归

    代码最为简洁,逻辑最清晰,最容易理解,性能最差。

    尾递归

    性能最好,代码逻辑稍微复杂。

    由此可见,不同的算法对程序的性能影响是十分巨大的,甚至是上千倍以上的差距。

    原文地址:https://www.cnblogs.com/haue/p/Fibonacci.html

    .NET社区新闻,深度好文,欢迎访问公众号文章汇总 http://www.csharpkit.com 


    最新回复(0)