• poj3070矩阵快速幂求斐波那契数列


     
    Fibonacci
    Time Limit: 1000MS   Memory Limit: 65536K
    Total Submissions: 13172   Accepted: 9368

    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


    思路:没得说,矩阵快速幂

    代码如下:

    #include <iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    const int mod = 10000;
    const int N = 2;//矩阵的维数,角标从0开始
    struct Matrix
    {
        __int64 v[N][N];
        Matrix()
        {
            memset(v,0,sizeof(v));
        }
    };
    //矩阵的乘法p1*p2
    Matrix multi(Matrix p1,Matrix p2)
    {
        Matrix res;
        for(int i=0;i<N;i++)
            for(int j=0;j<N;j++)
                if(p1.v[i][j])//代码优化,是0的话就不用计算
                    for(int k=0;k<N;k++)
                        res.v[i][k]=(res.v[i][k]+(p1.v[i][j]*p2.v[j][k]))%mod;
        return res;
    }
    //矩阵的快速幂p^k
    Matrix pow(Matrix p,__int64 k)
    {
        Matrix t;
        for(int i=0;i<N;i++)//初始化为单位矩阵
            t.v[i][i]=1;
        while(k)
        {
            if(k&1)
                t=multi(t,p);
            p=multi(p,p);
            k=k>>1;
        }
        return t;
    }
    
    
    int main()
    {
        __int64 n;
        Matrix e,ans;
        e.v[0][0]=e.v[0][1]=e.v[1][0]=1;
        e.v[1][1]=0;
        while(scanf("%I64dd",&n)!=EOF&&n!=-1)
        {
            ans = pow(e,n);
            printf("%I64d
    ",ans.v[0][1]);
        }
        return 0;
    }

     

  • 相关阅读:
    PostgreSQL在何处处理 sql查询之六十
    我对 PostgreSQL tidscan的理解
    PostgreSQL在何处处理 sql查询之五十九
    在PostgreSQL中,如何模拟Oracle的hint效果
    PostgreSQL在何处处理 sql查询之六十一
    PostgreSQL在何处处理 sql查询之五十八
    各种JOIN的理解
    对PostgreSQL源代码中的is_pushed_down的理解
    国外主流PHP框架比较
    图解什么是Web2.0
  • 原文地址:https://www.cnblogs.com/wt20/p/5782960.html
Copyright © 2020-2023  润新知