斐波那契数组-递归和循环实现

时间:2022-07-24
本文章向大家介绍斐波那契数组-递归和循环实现,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
static void Main(string[] args)
{
    Console.WriteLine(getnumfor(100));
    Console.ReadKey();
}
static long getnum(long index)
{
    if (index == 1 || index == 2)
    {
        return 1;
    }
    else
    {
        return getnum(index - 1) + getnum(index - 2);
    }
}
static long getnumfor(long index)
{
    if (index == 1 || index == 2)
    {
        return 1;
    }
    else
    {
        long one = 1; long two = 1;
        for (long i = 3; i <= index; i++)
        {
            if (i == 3)
            {
                one = 1;
                two = 1;
            }
            else
            {
                long temp = one;
                one = two;
                two = temp + two;
            }
        }
        return one + two;
    }
}