zoukankan      html  css  js  c++  java
  • POJ3070 Fibonacci(矩阵快速幂)

    用矩阵快速幂求fibonacci序列的第n项。

    /* ***********************************************
    Author        :devil
    Created Time  :2016/1/19 20:11:43
    ************************************************ */
    
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <cmath>
    #include <queue>
    #include <map>
    #include <set>
    #include <vector>
    #include <cstdio>
    using namespace std;
    const int MOD=1e4;
    struct matrix
    {
        int m[2][2];
    } ans,base;
    matrix multi(matrix a, matrix b)
    {
        matrix tmp;
        for(int i=0; i<2; ++i)
        {
            for(int j=0; j<2; ++j)
            {
                tmp.m[i][j]=0;
                for(int k=0; k<2; ++k)
                    tmp.m[i][j]=(tmp.m[i][j]+a.m[i][k]*b.m[k][j])%MOD;
            }
        }
        return tmp;
    }
    int fast_mod(int n)//求矩阵base的n次幂
    {
        base.m[0][0]=base.m[0][1]=base.m[1][0]=1;
        base.m[1][1]=0;
        ans.m[0][0]=ans.m[1][1]=1;//ans初始化为单位矩阵
        ans.m[0][1]=ans.m[1][0]=0;
        while(n)
        {
            if(n&1)//实现ans*=t;其中要先把ans赋值给tmp,然后用ans=tmp*t
                ans=multi(ans,base);
            base=multi(base,base);
            n>>=1;
        }
        return ans.m[0][1];
    }
    int main()
    {
        //freopen("in.txt","r",stdin);
        int n;
        while(scanf("%d",&n)&&n!=-1)
        {
            printf("%d
    ",fast_mod(n));
        }
        return 0;
    }
  • 相关阅读:
    网页HTML到8.20前
    数据库SQLServer
    构建之法读后感
    VS2013 生成安装文件
    工大助手(自动化部署)
    工大助手(用户名、密码错误提示)
    工大助手(验证码错误提示)
    工大助手(加权成绩计算)
    Wireshark插件编写
    微软认知服务——人脸识别
  • 原文地址:https://www.cnblogs.com/d-e-v-i-l/p/5143281.html
Copyright © 2011-2022 走看看