求斐波那契数列第n位的几种实现方式及性能对比
生活随笔
收集整理的這篇文章主要介紹了
求斐波那契数列第n位的几种实现方式及性能对比
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在每一種編程語言里,斐波那契數列的計算方式都是一個經典的話題。它可能有很多種計算方式,例如:遞歸、迭代、數學公式。哪種算法最容易理解,哪種算法是性能最好的呢?
這里給大家分享一下我對它的研究和總結:下面是幾種常見的代碼實現方式,以及各自的優缺點、性能對比。
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?
總結
以上是生活随笔為你收集整理的求斐波那契数列第n位的几种实现方式及性能对比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET开发人员如何开始使用ML.NET
- 下一篇: ASP.NET Core 3.0 自动挡