码迷,mamicode.com
首页 > 其他好文 > 详细

Fibnoccia 数列简单题

时间:2018-04-30 13:28:31      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:and   NPU   des   sso   inf   nta   ons   rod   enc   

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:

技术分享图片.

 

题目:一个矩阵快速幂就可以

代码示例:

#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;
    B.a[0][0] = B.a[1][1] = 1; // 单位矩阵
    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;
}

 

Fibnoccia 数列简单题

标签:and   NPU   des   sso   inf   nta   ons   rod   enc   

原文地址:https://www.cnblogs.com/ccut-ry/p/8973153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!