/// <summary>
/// Use recursive method to implement Fibonacci
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
static int Fn(int n)
{
if (n <= 0)
{
throw new ArgumentOutOfRangeException();
}
if (n == 1||n==2)
{
return 1;
}
return checked(Fn(n - 1) + Fn(n - 2)); // when n>46 memory will overflow
}
/// <summary>
/// Use three variables to implement Fibonacci
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
static int Fn1(int n)
{
if (n <= 0)
{
throw new ArgumentOutOfRangeException();
}
int a = 1;
int b = 1;
int c = 1;
for (int i = 3; i <= n; i++)
{
c = checked(a + b); // when n>46 memory will overflow
a = b;
b = c;
}
return c;
}
/// <summary>
/// Use less variables to implement Fibonacci
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
static int Fn2(int n)
{
if (n <= 0)
{
throw new ArgumentOutOfRangeException();
}
int a = 1;
int b = 1;
for (int i = 3; i <= n; i++)
{
b = checked(a + b); // when n>46 memory will overflow
a = b - a;
}
return b;
}