zoukankan      html  css  js  c++  java
  • 求斐波那契数列第n位的几种实现方式及性能对比(c#语言)

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

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

    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);
            }
        }
    }
    

    1.gif

    计算结果: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();
        }
    }
    

    2.gif

    计算结果: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();
        }
    }
    

    3.gif

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


    这几种实现方式总结:

    • 迭代

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

    • 递归

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

    • 尾递归

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

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

  • 相关阅读:
    Django 初试水(一)
    自己动手系列----使用数组实现一个简单的Set
    自己动手系列----使用数组实现一个简单的Map
    DB2中的MQT优化机制详解和实践
    Airy Memory 内存清理 + 注册码
    eclipse 工具翻译插件安装
    用sysdba登录oracle 11g数据库时遇到已连接到空闲例程 ora-013113
    Firewall 防火墙规则
    未找到段的定义
    ORACLE 锁表的解决方法 ORA-00054
  • 原文地址:https://www.cnblogs.com/haue/p/Fibonacci.html
Copyright © 2011-2022 走看看