zoukankan      html  css  js  c++  java
  • 快速幂模板

    const long long a=1000000000+7;
    int PowMod(long long n,long long p) { long long result=1; while (p>0) { if (p%2==1) { result=(result*n)%a; } p/=2; n=(n*n)%a; } return result; }
    n为底数,p为幂;a为要取模的数。

    矩阵快速幂求斐波那契数
    #include <cstdio>
    #include <iostream>
    using namespace std;
    const __int64 MOD=1e9;
    struct matrix
    {
        __int64 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;
    }
    __int64 fast_mod(__int64 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];
    }
    main()
    {
        __int64 n;
        int t,k;
        scanf("%d",&t);
        while(t--)
        {
            scanf("%d%I64d",&k,&n);   
        printf("%d %I64d
    ",k,fast_mod(n));
    }
    }
    
    
    
     
    
    
    
    
    
  • 相关阅读:
    购物车案例详解。利用cookie
    设计模式8种
    设计模式介绍
    Promise
    面向对象-拖拽
    本地存储
    闭包和继承
    move.js
    CDM指南之Agent管理
    失业的程序员九创业就是一场戏
  • 原文地址:https://www.cnblogs.com/CrazyBaby/p/5506778.html
Copyright © 2011-2022 走看看