• 矩阵乘法 快速幂 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, …
    Given two integers n and m, your goal is to compute the value of  Fn mod m.

    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) and m(where 0<m<=10000). The end-of-file is denoted by a single line containing the number −1 -1.

    Output

     For each test case, print the value of Fn%m one pre line, omit any leading zeros.

    Sample Input
    Copy sample input to clipboard
    0 10000
    9 10000
    999999999 10000
    1000000000 10000
    -1 -1
    
    Sample Output
    0
    34
    626
    6875
    #include<iostream>
    #include<cstring>
    using namespace std;
    struct mat{
        int matri[3][3];
    };
    inline mat MatMat(mat a,mat e,int m)
    {
        mat t;
        for(int i=0;i<2;++i)
            for(int k=0;k<2;++k)
            {
                t.matri[i][k]=0;    
                for(int j=0;j<2;++j)
                t.matri[i][k]=(t.matri[i][k]+a.matri[i][j]*e.matri[j][k])%m;
            }
        return t;               
    }
    
    inline int quick_mod(int q,int m)
    {
        mat I,a;
    
        a.matri[0][0]=0;
        a.matri[1][1]=a.matri[0][1]=a.matri[1][0]=1;
    
        I.matri[0][0]=I.matri[1][1]=1;
        I.matri[0][1]=I.matri[1][0]=0;
    
        while (q)
        {
            if(q&1) I=MatMat(a,I,m);
            a=MatMat(a,a,m);    
            q>>=1;  
        } 
        return I.matri[1][1];
    } //二分快速幂  
    
    int main()
    {
        int m,n;
        while(cin>>n>>m && n!=-1)
        {
            if(n==0 || n==1) {
                cout<<n<<endl;
                continue;
            }
            cout<<quick_mod(n-1,m)<<endl;
        } 
        return 0;
    } 
  • 相关阅读:
    学习SpringMVC——从HelloWorld开始
    线性队列
    线性表之链表
    线性表之顺序表
    nextSibling 属性与 nextElementSibling 属性的异同
    JavaScript数组增删方法总结
    class关键字
    JS三座大山_单线程&EventLoop
    JS三座大山_闭包
    JS三座大山_原型与原型链
  • 原文地址:https://www.cnblogs.com/tinyork/p/3460379.html
Copyright © 2020-2023  润新知