C#实现斐波那契数列

2019/01/16

203

最近,微软上线了在线编写C#,默认摸板是获取斐波那契数列

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        foreach (var i in Fibonacci().Take(20))
        {
            Console.WriteLine(i);
        }
    }

    private static IEnumerable<int> Fibonacci()
    {
        int current = 1, next = 1;

        while (true) 
        {
            yield return current;
            next = current + (current = next);
        }
    }
}

当然,我们也经常用来考递归算法,求第 n 位的数字是多少。

private static int Fibonacci(int index)
{
    if (index == 1 || index == 2)
        return 1;
    else if (index > 2)
        return Fibonacci(index - 2) + Fibonacci(index - 1);
    else
        throw new ArgumentException();
}
评论