Fibnoccia number sequence simple questions

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:

.

 

Topic: A fast power of a matrix is ​​enough

Code example:

#define ll long long
const ll maxn = 1e6+5;
const ll mod = 1e4;
const double eps = 1e-9;
const double pi = acos(-1.0);
const ll inf = 0x3f3f3f3f;

ll n;
struct mat
{
    ll a[2][2];
};

mat mul (mat A, mat B) {
    mat r;
    memset(r.a, 0, sizeof(r.a));
    
    for(ll i = 0; i < 2; i++){
        for(ll j = 0; j < 2; j++){
            for(ll k = 0; k < 2; k++){
                r.a[i][j] += (A.a[i][k]*B.a[k][j])%mod;
                r.a[i][j] %= mod;
            }
        }
    }
    return r;
}

mat qpow(mat A, ll x){
    mat B;
    Ba[0][0] = Ba[1][1] = 1; // identity matrix
    B.a[0][1] = B.a[1][0] = 0;
    
    while(x){
        if (x&1) B = mul(B, A);
        A = mul(A, A);
        x >>= 1;
    }
    return B;
}

int main() {
    //freopen("in.txt", "r", stdin);
    //freopen("out.txt", "w", stdout);
    
    while(~scanf("%lld", &n)){
        if (n == -1) break;
        
        mat a;
        a.a[0][0] = a.a[0][1] = a.a[1][0] = 1;
        a.a[1][1] = 0;
        
        if (n == 0) printf("0\n");
        else if (n == 1) printf("1\n");
        else {
            a = qpow(a, n-1);
            printf("%d\n", a.a[0][0]%mod);
        }
        
    }
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325113064&siteId=291194637
Recommended