zoukankan      html  css  js  c++  java
  • Fibonacci

    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:

    .

     

    #include<iostream>
    #include<cstring>
    using namespace std;
    #define For(i,a,b) for(int i=a;i<=b;i++)
    #define ll long long
    #define mem(a,b) memset(a,b,sizeof(a))
    #define mod 10000
    struct mat
    {
        ll m[3][3];
    };
    mat a,e;
    mat ans;
    int n;
    mat mul(mat a,mat b)
    {
        mat c;
        mem(c.m,0);
        For(i,1,2)
        For(j,1,2)
        For(k,1,2)
        {
            c.m[i][j]+=a.m[i][k]*b.m[k][j]%mod;
            c.m[i][j]%=mod;
        }
        return c;
    }
    mat qmul(mat a,ll b)
    {
        mat ans=e;
        while(b)
        {
            if(b&1)
                ans=mul(ans,a);
            a=mul(a,a);
            b>>=1;
        }
        return ans;
    }
    
    int main()
    {
        For(i,1,2)e.m[i][i]=1;
        mem(a.m,0);
        a.m[1][1]=a.m[1][2]=a.m[2][1]=1;
        while(cin>>n&&n!=-1)
        {
            if(n==0)
            {
                cout<<0<<endl;
                continue;
            }
            mat ans=qmul(a,n-1);
            cout<<ans.m[1][1]%mod<<endl;
        }
    
        return 0;
    }

    矩阵快速幂入门题

  • 相关阅读:
    特征的处理
    Pandas读取文件
    标准化数据-StandardScaler
    hibernate 继承映射
    hibernate 多对多关联映射
    hibernate 一对一关联映射
    hibernate 一对多 单双向关联
    hibernate配置文件
    spring整合struts2
    AWS云教育账号创建以及搭建数据库
  • 原文地址:https://www.cnblogs.com/planche/p/8605489.html
Copyright © 2011-2022 走看看