c#斐波那契数列(Fibonacci)(递归,非递归)实现代码
//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];
}
}
}
截图