# 斐波那契数列

    public int Fibonacci(int n)
{
if (n <= 0) return -1;
if (n == 1) return 0;
if (n == 2) return 1;
int[] nums = new int[n];
nums[0] = 0;
nums[1] = 1;
for (int i = 2; i < n; i++)
{
nums[i] = nums[i - 1] + nums[i - 2];
}
return nums[n - 1];
}

    public int Fibonacci(int n)
{
if (n <= 0) return -1;
int a = 0;
int b = 1;
for (int i = 0; i < n - 1; i++)
{
int c = a + b;
a = b;
b = c;
}
return a;
}

2018.5.4补充

An alternative formula for the Fibonacci sequence is:

 public class Matrix
{
public long a, b, c, d;

public Matrix(long a, long b, long c, long d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public Matrix() { }

public static Matrix MatrixMul(Matrix A, Matrix B)
{
Matrix m = new Matrix
{
a = A.a * B.a + A.b * B.c,
b = A.a * B.b + A.b * B.d,
c = A.c * B.a + A.d * B.c,
d = A.c * B.b + A.d * B.d
};
return m;
}

//二分法求矩阵幂
public static Matrix MatrixPow(int n)
{
Matrix m = new Matrix();
if (n == 1)
{
m = new Matrix(1, 1, 1, 0);
}
else if (n % 2 == 0)
{
m = MatrixPow(n / 2);
m = MatrixMul(m, m);
}
else if (n % 2 == 1)
{
m = MatrixPow((n - 1) / 2);
m = MatrixMul(m, m);
m = MatrixMul(m, new Matrix(1, 1, 1, 0));
}
return m;
}
}

    public string Fibonacci(int n)
{
if (n == 0) return "0";
if (n == 1) return "1";
Matrix m = Matrix.MatrixPow(n);
string s = m.b.ToString();
return s;
}