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, …
    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;
    } 
  • 相关阅读:
    web-火狐浏览器下载地址
    如何使用jmeter录制app脚本
    Jmeter参数化(jmter和badboy的配合使用)
    monkey常用命令详解(多参数化)
    monkey常用命令
    mysql数据库命令
    Linux命令
    循环语句的使用
    K8S学习笔记一:K8S的基础概念
    jmeter做尖峰测试(浪潮测试)
  • 原文地址:https://www.cnblogs.com/tinyork/p/3460379.html
Copyright © 2011-2022 走看看