sicily 1001. Fibonacci 2

本文介绍了一种使用矩阵快速幂算法高效计算Fibonacci数列第n项的方法,通过将Fibonacci递推公式转换为矩阵乘法形式,可以大幅度减少计算时间复杂度,尤其适用于大整数的计算场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                              1001. Fibonacci 2
 
Description
In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn-1 + Fn-2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:
 
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
 
Given an integer n, your goal is to compute the last Fn mod (10^9 + 7).
Input

 The input test file will contain a single line containing n (n ≤ 2^31-1).

There are multiple test cases!

 

 

Output

 For each test case, print the Fn mod (10^9 + 7).

Sample Input
 Copy sample input to clipboard 
9
Sample Output
34

用矩阵快速幂的方法,具体可见: http://blog.csdn.net/ACdreamers/article/details/25616461

#include <iostream>

using namespace std;

#define M 1000000007

struct Matrix{
    long long v[2][2];
};

Matrix matrixMul(Matrix a, Matrix b) {
    Matrix temp;
    for (int i = 0; i != 2; i++) {
        for (int j = 0; j != 2; j++) {
            temp.v[i][j] = 0;
            for (int k = 0; k != 2; k++) {
                temp.v[i][j] += a.v[i][k] * b.v[k][j];
                temp.v[i][j] %= M;
            }
        }
    }
    return temp;
}

Matrix power(Matrix a, Matrix b, long long n) {
    while (n) {
        if (n & 1) {
            b = matrixMul(b, a);
        }
        n >>= 1;
        a = matrixMul(a, a);
    }
    return b;
}

int main(int argc, char* argv[]) 
{
    Matrix a = {1, 1, 1, 0}, b = {1, 0, 0, 1};
    long long n;
    while (cin >> n) {
        if (n == 0)
            cout << 0 << endl;
        else {
            Matrix result = power(a, b, n - 1);
            cout << result.v[0][0] << endl;
        }
    }

    return 0;
}

 

 

转载于:https://www.cnblogs.com/xiezhw3/p/3997190.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值