使用C#编写求解斐波那契数列的函数

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的斐波那契数列结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值