C#斐波那契数列求法(比较阶乘和循环所用时间)
程序员文章站
2022-06-13 08:22:16
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); } } } }
上一篇: thinkphp5 + barcode 生成条形码
下一篇: 马戏团