POJ_3070 矩阵快速幂实现斐波那契数列变化

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

题意理解:读题可知,斐波那契的转移矩阵已经在题目中给出,并且初始矩阵和转移矩阵是相同的,所以直接就是个矩阵快速幂的裸题。

代码:

#include <iostream>
#include <cstring>
#define ll long long
using namespace std;
const int Mod = 10000;
struct Matrix
{
    int m[3][3];
};

Matrix multi(Matrix a, Matrix b)
{
    Matrix ans;
    memset(ans.m, 0, sizeof(ans.m));
    for(int i = 1; i < 3; i++)
        for(int j = 1; j < 3; j++)
            for(int k = 1; k < 3; k++)
                ans.m[i][j] = (ans.m[i][j] + a.m[i][k]*b.m[k][j] % Mod) % Mod;
    return ans;
}

Matrix pow(Matrix a, ll n)
{
    Matrix ans;
    memset(ans.m, 0, sizeof(ans.m));
    for(int i = 1; i < 3; i++)
        ans.m[i][i] = 1;
    while(n)
    {
        if(n&1)
            ans = multi(ans, a);
        n >>= 1;
        a = multi(a, a);
    }
    return ans;
}

int main()
{
    Matrix ans;
    memset(ans.m, 0, sizeof(ans.m));
    ans.m[1][1] = 1, ans.m[1][2] = 1, ans.m[2][1] = 1;
    ll n;
    while(cin >> n && n != -1)
    {
        if(n == 0)
        {
            cout << "0" << endl;
            continue;
        }
        if(n == 1 || n == 2)
        {
            cout << "1" << endl;
            continue;
        }
        memset(ans.m, 0, sizeof(ans.m));
        ans.m[1][1] = 1, ans.m[1][2] = 1, ans.m[2][1] = 1;
        ans = pow(ans, n-1);
        cout << ans.m[1][1] << endl;

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PrinceJin_Dybala/article/details/81392763