C#斐波那契数列求法(比较阶乘和循环所用时间)

using System;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("你要输入多少项?");
            int a = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine();
            DateTime dt1 = System.DateTime.Now;
            for (int i = 1; i <= a; i++)
            {
                Console.Write("\t{0}", J(i));
                if (i % 5 == 0)
                {
                    Console.WriteLine();
                }
            }
            DateTime dt2 = System.DateTime.Now;
            TimeSpan ts = dt2.Subtract(dt1);
            Console.WriteLine("3变量循环方法用时{0}", ts.TotalMilliseconds);//3变量循环方法所用时间

            DateTime dt11 = System.DateTime.Now;
            for (int i = 1; i <= a; i++)
            {
                Console.Write("\t{0}", J1(i));
                if (i % 5 == 0)
                {
                    Console.WriteLine();
                }
            }
            DateTime dt22 = System.DateTime.Now;
            TimeSpan ts1 = dt22.Subtract(dt11);
            Console.WriteLine("2变量循环方法用时{0}", ts1.TotalMilliseconds);//2变量循环方法所用时间

            DateTime dt111 = System.DateTime.Now;
            for (int i = 1; i <= a; i++)
            {
                Console.Write("\t{0}", J2(i));
                if (i % 5 == 0)
                {
                    Console.WriteLine();
                }
            }
            DateTime dt222 = System.DateTime.Now;
            TimeSpan ts11 = dt222.Subtract(dt111);
            Console.WriteLine("递归方法用时{0}", ts11.TotalMilliseconds);//递归方法所用时间
        }
        /// 
        /// 3个变量循环求斐波那契数列
        /// 
        /// 
        /// 
        static int J(int b)
        {
            int x = 1;
            int y = 1;
            if (b == 1 || b == 2)
            {
                return 1;
            }
            else
            {
                for (int i = 3; i <= b; i++)
                {
                    int z = x + y;
                    y = x;
                    x = z;
                }
                return x;
            }
        }
        /// 
        /// 2个变量循环求斐波那契数列
        /// 
        /// 
        /// 
        static int J1(int b)
        {
            int x = 1;
            int y = 1;
            if (b == 1 || b == 2)
            {
                return 1;
            }
            else
            {
                for (int i = 3; i <= b; i++)
                {
                    y = x + y;
                    x = y-x;
                }
                return y;
            }
        }

        /// 
        /// 阶乘求斐波那契数列
        /// 
        /// 
        /// 
        static int J2(int b)
        {
            if (b == 1 || b == 2)
            {
                return 1;
            }
            else
            {
                return J2(b - 1) + J2(b - 2);
            }
        }
    }
}

 

你可能感兴趣的:(C#斐波那契数列求法(比较阶乘和循环所用时间))