求斐波纳契数列第30位数字是多少?递归算法和普通算法

class Program18
    {
        public static int Fbnq(int i)
        {
            if (i <= 0)
            {
                return 0;
            }
            else if (i <= 2)
            {
                return 1;
            }
            else
            {
                return Fbnq(i - 2) + Fbnq(i - 1);
            }
        }
        /// <summary>
        /// 斐波那契数列,普通算法
        /// </summary>
        /// <param name="num">第num位数的值</param>
        /// <returns></returns>
        public static int FbnqSort2(int num)
        {
            int ret = 0;
            int num1 = 1;
            int num2 = 1;
            for (int i = 0; i < num - 2; i++)
            {
                ret = num1 + num2;
                num1 = num2;
                num2 = ret;
            }
            return ret;
        }

        static void Main(string[] args)
        {
            for (int i = 1; i <= 20; i++)
            {
                Console.Write(Fbnq(i));
                Console.Write(" ");
            }
            Console.WriteLine();
            Console.WriteLine(Fbnq(30));
            Console.WriteLine(FbnqSort2(30));
            Console.ReadLine();
        }
    }

 

posted @ 2018-10-30 21:13  幸福安康  阅读(874)  评论(0编辑  收藏  举报