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

01/19/2019 21:15:58 阅读(1728)

斐波那契数列有很多种计算方式,例如:递归、迭代、数学公式。下面是几种常见的代码实现方式,以及各自的优缺点、性能对比。

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


这几种实现方式总结:

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

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

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

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

返回