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

网友投稿 264 2022-08-01

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);

}

}

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:浅拷贝与深拷贝(浅拷贝与深拷贝Java实现)
下一篇:NPOI 导出 excel 性能测试(npoi写入excel)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~