using System;
using System.Numerics;
namespace Fibonacci
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetFibonacciNumber(8000));
}
static BigInteger GetFibonacciNumber(int n)
{
BigInteger[,] matrix = new BigInteger[,] { { 1, 1 }, { 1, 0 } };
BigInteger[,] result = Power(matrix, n);
return result[0, 0];
}
static BigInteger[,] Power(BigInteger[,] matrix, int n)
{
if (n == 1)
{
return matrix;
}
BigInteger[,] subResult = Power(matrix, n / 2);
BigInteger[,] result = Multiply(subResult, subResult);
if (n % 2 == 1)
{
result = Multiply(result, matrix);
}
return result;
}
static BigInteger[,] Multiply(BigInteger[,] a, BigInteger[,] b)
{
BigInteger[,] c = new BigInteger[2, 2];
c[0, 0] = a[0, 0] * b[0, 0] + a[0, 1] * b[1, 0];
c[0, 1] = a[0, 0] * b[0, 1] + a[0, 1] * b[1, 1];
c[1, 0] = a[1, 0] * b[0, 0] + a[1, 1] * b[1, 0];
c[1, 1] = a[1, 0] * b[0, 1] + a[1, 1] * b[1, 1];
return c;
}
}
}
PS:使用BigInteger确保可以保存任意大小的整数,输出任意大小的n的斐波那契数列结果