using System; namespace ConsoleApp3 { class Program { static void Main(string[] args) { Console.Write("你要輸入多少項?"); int a = Convert.ToInt32(Console.Rea ...
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);//遞歸方法所用時間 } /// <summary> /// 3個變數迴圈求斐波那契數列 /// </summary> /// <param name="b"></param> /// <returns></returns> 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; } } /// <summary> /// 2個變數迴圈求斐波那契數列 /// </summary> /// <param name="b"></param> /// <returns></returns> 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; } } /// <summary> /// 階乘求斐波那契數列 /// </summary> /// <param name="b"></param> /// <returns></returns> static int J2(int b) { if (b == 1 || b == 2) { return 1; } else { return J2(b - 1) + J2(b - 2); } } } }