好玩的Fibonacci数列

1.原理:

不做过多解释,不会去翻高中数学教材

2.重要结论:

  1.前n项和 可以 用 n + 2项的数减一得到

计算方法:

  矩阵快速幂!!!

上板子题:

                                 Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 21213   Accepted: 14511

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, …

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 <vector>
#include <iostream>


using namespace std;

typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;

const ll  mod = 10000;

mat mul(mat & A, mat& B) {
    mat C(A.size(), vec(B[0].size()));
    for (int i = 0; i < A.size(); ++i)
        for (int k = 0; k < B.size(); ++k)
            if (A[i][k])
                for (int j = 0; j < B[0].size(); ++j)
                    C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % mod;
    return C;            
}


mat Pow(mat A, ll n) {
    mat B(A.size(), vec(A.size()));
    for (int i = 0; i < A.size(); ++i)
        B[i][i] = 1;
    for (; n; n >>= 1, A = mul(A, A))
        if(n & 1)
            B = mul(B, A);
    return B;
}


int main (){
    mat A(2);

    A.resize(2);//r行
    for (int k = 0; k < 2; ++k){
        A[k].resize(2);//每行为c列
    }

    A[0][0] = 1;
    A[0][1] = 1;
    A[1][0] = 1;
    A[1][1] = 0;


    ll n;
    while(cin >> n && n != -1) {
        if (n) {
            mat C = Pow(A, n - 1);
            cout << C[0][0] << endl;
        }
        else
            cout << 0 << endl;       
    }
}
 

猜你喜欢

转载自www.cnblogs.com/lightac/p/10630320.html