poj 3070 斐波拉切快速幂公式

Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 14923   Accepted: 10496

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

涨姿势了不是,斐波拉切的快速幂公式就在这里,解决了n很大是递归公式爆栈的问题吧

注意n=0特判即可

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

typedef long long ll;
const int maxn = 4;
const int mod = 10000;
struct mat {
    int s[maxn][maxn];
    mat(){
        memset(s,0,sizeof(s));
    };
    mat operator * (const mat& c) {
    mat ans;
    for (int i = 0; i < maxn; i++) //矩阵乘法
        for (int j = 0; j < maxn; j++)
            for (int k = 0; k < maxn; k++)
                ans.s[i][j] = (ans.s[i][j] + s[i][k] * c.s[k][j]) % mod;
    return ans;
    }
}str;

mat pow_mod(ll k) {
    if (k == 1)
        return str;
    mat a = pow_mod(k/2);//不能改
    mat ans = a * a;
    if (k & 1)
        ans = ans * str;
    return ans;
}


int main() {
    //freopen("in.txt","r",stdin);
    int n;
    str.s[0][0] = 1;
    str.s[0][1] = 1;
    str.s[1][0] = 1;
    str.s[1][1] = 0;
    while(~scanf("%d",&n)&&n!=-1) {
        if(n==0)
            puts("0");
        else {
            mat sub = pow_mod(n);
            ll res = 0;
            res = sub.s[0][1]%mod;
            cout<<res<<endl;
        }
    }
    return 0;
}


posted @ 2017-05-01 15:06  Lawliet__zmz  阅读(200)  评论(0编辑  收藏  举报