手机
当前位置:查字典教程网 >编程开发 >C#教程 >c#斐波那契数列(Fibonacci)(递归,非递归)实现代码
c#斐波那契数列(Fibonacci)(递归,非递归)实现代码
摘要://Main复制代码代码如下:usingSystem;usingSystem.Collections.Generic;usingSystem...

//Main

复制代码 代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Fibonacci

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Would you like to know which Fibonacci Numbers:");

int number = Convert.ToInt32(Console.ReadLine());

//

Function obj = new Function();

Console.WriteLine();

Console.Write("The {0} Fibonacci number is:{1}", number, obj.Fibonacci(number));

//

Console.WriteLine();

Function obj2 = new Function(number);

Console.Write("The {0} Fibonacci number is:{1}", number, obj2.BottomUpNotRecursion(number));

//

Console.WriteLine();

Console.Write("The {0} Fibonacci number is:{1}", number, obj2.TopDownRecursion(number));

Console.ReadKey();

}

}

}

//Class

复制代码 代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Fibonacci

{

class Function

{

private int[] array;

public Function()

{

}

/// <summary>

/// Function

/// </summary>

/// <param name="length"></param>

public Function(int length)

{

if (length > 0)

{

array = new int[length + 1];

array[0] = 1;

array[1] = 1;

}

if (length == 0)

{

array = new int[1];

array[0] = 1;

}

}

/// <summary>

/// Fibonacci数列定义为:

/// 无穷数列1,1,2,3,5,8,13,21,34,55,……

/// ┌ 1 n=0

/// F(n)=│ 1 n=1

/// └ F(n-1)+F(n-2) n>1

/// </summary>

/// <param name="number">第几个斐波那契数</param>

/// <returns></returns>

public int Fibonacci(int number)

{

if (number <= 1)

{

return 1;

}

else

{

return Fibonacci(number - 1) + Fibonacci(number - 2);

}

}

/// <summary>

/// 动态规划思想:

/// 1.自底向上非递归算法

/// </summary>

/// <param name="number"></param>

/// <returns></returns>

public int BottomUpNotRecursion(int number)

{

int copynumber = 0;

if (number < 2)

{

copynumber = 1;

}

else

{

int one = array[0];

int two = array[1];

for (int i = 2; i < array.Length; i++)

{

array[i] = one + two;

one = two;

two = array[i];

copynumber = array[i];

}

}

return copynumber;

}

/// <summary>

/// 2.自顶向下递归算法

/// </summary>

/// <param name="number"></param>

/// <returns></returns>

public int TopDownRecursion(int number)

{

if (number <= 2)

{

if (number == 0)

return array[0];

if (number == 1)

return array[1];

if (number == 2)

return array[2] = array[0] + array[1];

}

else

{

//递归只是一个“牵引线”,目的是为了让数组储存值。

TopDownRecursion(number - 1);

array[number] = array[number - 1] + array[number - 2];

}

return array[number];

}

}

}

截图

c#斐波那契数列(Fibonacci)(递归,非递归)实现代码1

【c#斐波那契数列(Fibonacci)(递归,非递归)实现代码】相关文章:

C#求解哈夫曼树,实例代码

学习C#静态函数及变量的一个精典例子与代码

c#文件的复制,移动,创建(实例代码)

c#中的浮点型转整形的舍取 四舍五入和银行家舍入实现代码

List转换成DataSet实现代码

c# 调用.bat文件的实现代码

C#程序最小化到托盘图标操作步骤与实现代码

C# 无边框窗体之窗体移动实现代码

C# 邮件发送和接收实现代码

C#自动创建数据库实现代码

精品推荐
分类导航