Fibonacci (矩阵快速幂)

本文介绍了一种高效计算斐波那契数列第n项最后四位数字的方法,利用矩阵乘法和快速幂运算,解决了大规模数值计算的问题,并提供了一个具体的C++实现示例。
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, …

An alternative formula for the Fibonacci sequence is

                            

Given an integer n, your goal is to compute the last 4 digits of Fn.

Input
The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

Output
For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875
Hint
As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

                             

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

                                                          


  AC代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<time.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<vector>
#include<bitset>
using namespace std;
const int mod=10000;
struct Matrix{
    int n,m; //大小
    int d[5][5];
    Matrix(int a=0,int b=0){
        n=a,m=b;
        memset(d,0,sizeof(d));
    }
    void copy(int *tmp){
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++){
                d[i][j]=(*tmp)%mod;
                ++tmp;  //指针 指向要传入数组的某个元素
            }
    }
    friend Matrix operator * (const Matrix &a,const Matrix &b){ //矩阵乘法的重载
        Matrix c(a.n,b.m);
        for (int i=0; i<a.n; ++i)
            for (int j=0; j<b.m; ++j){
                long long tmp=0;
                for (int k=0; k<a.m; ++k){
                    tmp+=(long long)a.d[i][k]*b.d[k][j] % mod;
                    tmp%=mod;
                }
                c.d[i][j]=tmp % mod;
            }
        return c;
    }
};
int solve(int n){
    if (n==0) return 0;
    if (n==1) return 1;
    Matrix A(1,2),B(2,2);
    int aa[2]={0,1};
    int bb[2*2]={
        0,1,
        1,1,
    };
    A.copy(aa);//矩阵的构造函数copy
    B.copy(bb);
    for (int k=n; k; k>>=1){
        if (k&1)
            A=A*B;
        B=B*B;
    }
    return A.d[0][0];
}

int main()
{
    int n=0;
    while(scanf("%d",&n)!=EOF){
        if (n==-1) break;
        printf("%d\n",solve(n));
    }
    return 0;
}


### C++ 实现 Fibonacci 数列的矩阵快速幂算法 以下是一个基于矩阵快速幂方法实现的 C++ 示例代码,用于高效计算斐波那契数列的第 \( n \) 项。此方法的时间复杂度为 \( O(\log{n}) \),相较于传统的线性迭代方法更加高效。 ```cpp #include <iostream> #include <vector> using namespace std; const long long MOD = 1e9 + 7; // 定义矩阵结构体 struct Matrix { vector<vector<long long>> data; int rows, cols; Matrix(int r, int c) : rows(r), cols(c), data(vector<vector<long long>>(r, vector<long long>(c, 0))) {} }; // 矩阵乘法函数 Matrix multiply(const Matrix& a, const Matrix& b) { Matrix res(a.rows, b.cols); for (int i = 0; i < a.rows; ++i) { for (int j = 0; j < b.cols; ++j) { for (int k = 0; k < a.cols; ++k) { res.data[i][j] = (res.data[i][j] + a.data[i][k] * b.data[k][j]) % MOD; } } } return res; } // 矩阵快速幂函数 Matrix matrixPower(Matrix base, long long exp) { Matrix res(base.rows, base.cols); for (int i = 0; i < base.rows; ++i) res.data[i][i] = 1; // 初始化单位矩阵 while (exp > 0) { if (exp % 2 == 1) { res = multiply(res, base); } base = multiply(base, base); exp /= 2; } return res; } long long fibonacci(long long n) { if (n == 0) return 0; if (n == 1) return 1; Matrix T(2, 2); // 转移矩阵 [[1, 1], [1, 0]] T.data[0][0] = 1; T.data[0][1] = 1; T.data[1][0] = 1; T.data[1][1] = 0; Matrix F(2, 1); // 初始状态向量 [[1], [0]] F.data[0][0] = 1; F.data[1][0] = 0; T = matrixPower(T, n - 1); // 计算T^(n-1) F = multiply(T, F); return F.data[0][0]; // 返回结果即为F[n] } int main() { long long n; cin >> n; cout << "Fibonacci number at position " << n << " is: " << fibonacci(n) << endl; return 0; } ``` #### 解析 1. **矩阵定义** 使用 `Matrix` 结构体表示二维矩阵,并支持初始化和存储操作[^4]。 2. **矩阵乘法** 函数 `multiply` 实现两个矩阵之间的乘法运算,同时对结果取模以防止溢出[^3]。 3. **矩阵快速幂** 函数 `matrixPower` 借助分治思想实现了高效的矩阵幂次计算,其核心逻辑类似于整数快速幂算法[^2]。 4. **初始条件与转移矩阵** 斐波那契数列的状态可以通过如下关系表达: \[ \begin{bmatrix} f_{n+1} \\ f_n \end{bmatrix} = \begin{bmatrix} 1 & 1 \\ 1 & 0 \end{bmatrix}^n \cdot \begin{bmatrix} f_1 \\ f_0 \end{bmatrix} \] 5. **最终结果提取** 对于输入 \( n \geq 2 \),通过计算 \( T^{n-1} \times F \) 得到目标值 \( f_n \)[^5]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值