C#算法从入门到跑路 第0章:斐波那契数列

1.斐波那契数列:

n=0: F[n]=0
n=1: F[n]=1
n>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));
    }
}

csharper
1 声望3 粉丝

曲终过尽松陵路,回首烟波十四桥。