Fibonacci
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 17432   Accepted: 12167

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

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:

.

Source


#include <stdio.h>
#include <iostream>
#include <string.h>
#pragma comment(linker, "/STACK:102400000,102400000")
#define INF 0x3f3f3f3f
#define MOD 10000
#define bug cout << "bug" << endl


using namespace std;
typedef long long ll;

const int MAX_N=3;
int n,m;

void multi(ll a[MAX_N][MAX_N],ll b[MAX_N][MAX_N]){
    ll temp[MAX_N][MAX_N];
    memset(temp,0,sizeof(temp));
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            for(int k=1;k<=2;k++){
                temp[i][j]+=a[i][k]*b[k][j]%MOD;
                temp[i][j]%=MOD;
            }
        }
    }
    for(int i=1;i<=2;i++)
        for(int j=1;j<=2;j++)   a[i][j]=temp[i][j];
}

void pow_matrix(ll a[MAX_N][MAX_N],int m){
    ll ans[MAX_N][MAX_N];
    memset(ans,0,sizeof(ans));
    for(int i=1;i<=2;i++)   ans[i][i]=1;
    while(m){
        if(m&1) multi(ans,a);
        multi(a,a);
        m>>=1;
    }
//    for(int i=1;i<=n;i++){
//        for(int j=1;j<=n;j++){
//            if(j==1)    printf("%lld",ans[i][j]);
//            else    printf(" %lld",ans[i][j]);
//        }
//        printf("\n");
//    }
//    for(int i=1;i<=2;i++){
//        for(int j=1;j<=2;j++)   printf("%lld ",ans[i][j]);
//        puts("");
//    }
    cout << ans[1][1]<<endl;
}

int main(void){
    while(cin >> m){
        if(m==0){
            printf("0\n");
            continue;
        }
        if(m==-1)   break;
        ll a[MAX_N][MAX_N];
        a[1][1]=a[1][2]=a[2][1]=1,a[2][2]=0;
        pow_matrix(a,m-1);
    }
    return 0;
}
/*

*/