【模板】阶乘预处理+组合数、模逆元、矩阵快速幂

阶乘预处理+组合数

#include <bits/stdc++.h>
#define endl '\n'
#define int long long
const int MOD = 1e9 + 7;
using namespace std;

const int MAX = 1000000 + 10; // 1e6 + 10
long long fact[MAX], inv_fact[MAX];

long long pow_mod(long long a, long long b) {
    long long res = 1;
    while (b > 0) {
        if (b & 1)
            res = res * a % MOD;
        a = a * a % MOD;
        b >>= 1;
    }
    return res;
}

void precompute() {
    fact[0] = 1;
    for (int i = 1; i < MAX; ++i) {
        fact[i] = fact[i - 1] * i % MOD;
    }
    inv_fact[MAX - 1] = pow_mod(fact[MAX - 1], MOD - 2);
    for (int i = MAX - 2; i >= 0; --i) {
        inv_fact[i] = inv_fact[i + 1] * (i + 1) % MOD;
    }
}

long long comb(int a, int b) {
    if (b < 0 || b > a)
        return 0;
    return fact[a] * inv_fact[b] % MOD * inv_fact[a - b] % MOD;
}

void solve() {
    // comb(n,m);
}

signed main() {
    precompute();
    int T = 1;
    cin >> T;
    while (T--) {
        solve();
    }
    return 0;
}

模逆元

// 使用费马小定理计算模逆元(要求mod为质数)。
typedef long long ll;
const ll mod = 1e9 + 7;

ll mod_pow(ll a, ll b, ll mod) {
    ll res = 1;
    while (b) {
        if (b & 1)
            res = res * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return res;
}

ll mod_inverse(ll x) { return mod_pow(x, mod - 2, mod); }
//扩展欧几里得算法,不需要mod为质数
void extend_gcd(ll a, ll b, ll &d, ll &x, ll &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        d = a;
        return;
    }
    extend_gcd(b, a % b, d, x, y);
    ll tmp = x;
    x = y;
    y = tmp - a / b * y;
}

ll mod_reverse(ll y, ll p) {
    ll x, d;
    extend_gcd(y, p, d, x, y);
    return d == 1 ? (p + x % p) % p : -1;
}

矩阵快速幂

//矩阵快速幂 斐波那契数列
public int Fibonacci(int n)
    {
        n--;//矩阵为两项
        int a[][]= {{1,1},{1,0}};//进行快速幂的矩阵
        int b[][]={{1,0},{0,1}};//存储漏单奇数、结果的矩阵,初始为单位矩阵
        int time=0;
        while(n>0)
        {
            if(n%2==1)
            {
                b=matrixMultiplication(a, b);
            }
            a=matrixMultiplication(a, a);
            n/=2;
        }
        return b[0][0];
    }
 public  int [][]matrixMultiplication(int a[][],int b[][]){//
        int x=a.length;//a[0].length=b.length 为满足条件
        int y=b[0].length;//确定每一排有几个
        int c[][]=new int [x][y];
        for(int i=0;i<x;i++)
            for(int j=0;j<y;j++)
            {
                //需要确定每一个元素
                //c[i][j];
                for(int t=0;t<b.length;t++)
                {
                    c[i][j]+=(a[i][t]%10000)*(b[t][j]%10000);
                    c[i][j]%=10000;
                }
            }
        return c;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值