求斐波那契数列
斐波那契数列 : 0 1 1 2 3 5 8 13 21 34 55 89
规律 :n = (n-1)+(n-2)
1. 递归实现
public static UInt64 GetResult(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
return GetResult(n - 1) + GetResult(n-2);
}
如此计算,过程中会许多重复的计算过程,导致之间复杂度为2^n,其运算时间过长,并不推荐。
2. 其他算法
public static UInt64 GetResult(int n)
{
UInt64 firstNum = 1;
UInt64 secNum = 1;
if (n == 0)
return 0;
else if (n == 1)
return 1;
for (int i = 3; i <= n; i++)
{
UInt64 sum = firstNum + secNum;
firstNum = secNum;
secNum = sum;
}
return secNum;
}