C#アルゴリズム入門から走路0章:フィボナッチ数列


C#アルゴリズム入門から走路0章:フィボナッチ数列
1.フィボナッチ数列:
n=0: F[n]=0n=1: F[n]=1n>1: F[n]=F[n-1]+F[n-2]
1.再帰形式
using System;
using static System.Console;
class Test
{
    public static void Main(string[] args)
    {
        //      
        int fib(int n)
        {
            if (n <= 1) return n;
            else return fib(n - 1) + fib(n - 2);
        }
        WriteLine(fib(4));
    }
}

2.循環形式
using System;
using System.Collections.Generic;
using static System.Console;
using static MyUtil;
class Test
{
    public static void Main(string[] args)
    {
        //      
        long fib(long n)
        {
            if (n <= 1) return n;
            var (first, second) = (0L, 1L);
            var sum = 0L;
            foreach (var item in range(2,n))
            {
                sum = first + second;
                first = second;
                second = sum;
            }
            return second;
        }
        WriteLine(fib(70));
    }
}