F1: 迭代法
最慢,复杂度最高
F2: 直接法
F3: 矩阵法
参考《算法之道(The Way of Algorithm)》第38页-魔鬼序列:斐波那契序列
F4: 通项公式法
由于公式中包含根号5,无法取得精确的结果,数字越大误差越大
using System;
using System.Diagnostics; namespace Fibonacci
{
class Program
{
static void Main(string[] args)
{
ulong result; int number = ;
Console.WriteLine("************* number={0} *************", number); Stopwatch watch1 = new Stopwatch();
watch1.Start();
result = F1(number);
watch1.Stop();
Console.WriteLine("F1({0})=" + result + " 耗时:" + watch1.Elapsed, number); Stopwatch watch2 = new Stopwatch();
watch2.Start();
result = F2(number);
watch2.Stop();
Console.WriteLine("F2({0})=" + result + " 耗时:" + watch2.Elapsed, number); Stopwatch watch3 = new Stopwatch();
watch3.Start();
result = F3(number);
watch3.Stop();
Console.WriteLine("F3({0})=" + result + " 耗时:" + watch3.Elapsed, number); Stopwatch watch4 = new Stopwatch();
watch4.Start();
double result4 = F4(number);
watch4.Stop();
Console.WriteLine("F4({0})=" + result4 + " 耗时:" + watch4.Elapsed, number); Console.WriteLine(); Console.WriteLine("结束");
Console.ReadKey();
} /// <summary>
/// 迭代法
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private static ulong F1(int number)
{
if (number == || number == )
{
return ;
}
else
{
return F1(number - ) + F1(number - );
} } /// <summary>
/// 直接法
/// </summary>
/// <param name="number"></param>
/// <returns></returns>
private static ulong F2(int number)
{
ulong a = , b = ;
if (number == || number == )
{
return ;
}
else
{
for (int i = ; i <= number; i++)
{
ulong c = a + b;
b = a;
a = c;
}
return a;
}
} /// <summary>
/// 矩阵法
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
static ulong F3(int n)
{
ulong[,] a = new ulong[, ] { { , }, { , } };
ulong[,] b = MatirxPower(a, n);
return b[, ];
} #region F3
static ulong[,] MatirxPower(ulong[,] a, int n)
{
if (n == ) { return a; }
else if (n == ) { return MatirxMultiplication(a, a); }
else if (n % == )
{
ulong[,] temp = MatirxPower(a, n / );
return MatirxMultiplication(temp, temp);
}
else
{
ulong[,] temp = MatirxPower(a, n / );
return MatirxMultiplication(MatirxMultiplication(temp, temp), a);
}
} static ulong[,] MatirxMultiplication(ulong[,] a, ulong[,] b)
{
ulong[,] c = new ulong[, ];
for (int i = ; i < ; i++)
{
for (int j = ; j < ; j++)
{
for (int k = ; k < ; k++)
{
c[i, j] += a[i, k] * b[k, j];
}
}
}
return c;
}
#endregion /// <summary>
/// 通项公式法
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
static double F4(int n)
{
double sqrt5 = Math.Sqrt();
return (/sqrt5*(Math.Pow((+sqrt5)/,n)-Math.Pow((-sqrt5)/,n)));
}
}
}
n=50时
n=500
n=5000
n=50000
n=5000000