斐波那契数列(Fibonacci Number)从数学的角度是以递归的方法定义的:
- (F_0 = 0)
- (F_1 = 1)
- (F_n = F_{n-1} + F_{n-2}) ((n geq 2))
C# 的递归算法实现如下:
/// <summary>
/// 返回指定序数的 Fibonacci number
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public int FibonacciNumber(int index)
{
if (index == 0)
{
return 0;
}
else if (index == 1)
{
return 1;
}
else
{
return FibonacciNumber(index - 1) + FibonacciNumber(index - 2);
}
}