BZOJ 1951 费马小定理 + Lucas定理 + 乘法逆元 + 中国剩余定理 + 快速幂

题意: 给定n, g
gd|nC(n,d)modp
1. 质因数分解可得p是质数, 用费马小定理转成求:

d|nC(n,d)mod(p1)

2. 枚举n的约数, 考虑用Lucas定理求C(n,d) % (p - 1)
3. p - 1是大合数, 把它质因数分解得到四个质数, 设为p i,用Lucas定理求 d|nC(n,d)mod(pi) , 注意到最大的质数35617还是很大, 所以用乘法逆元
4. 中国剩余定理求
d|nC(n,d)mod(p1)

5. 快速幂求解
6. 特判g % p == 0的情况


code

/**************************************************************
    Problem: 1951
    User: adrui
    Language: C++
    Result: Accepted
    Time:124 ms
    Memory:2416 kb
****************************************************************/

#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;

#define left Left
const ll p = 999911659;

ll mod[] = {2, 3, 4679, 35617}, left[4];
ll fac[36000][4];/**存n!%pi*/
ll n, g;

void getFac(){/**预处理*/
    fac[0][0] = fac[0][1] = fac[0][2] = fac[0][3] = 1;
    for(int i = 1; i < 36000; ++i)
        for(int j = 0; j < 4; ++j)
            fac[i][j] = fac[i - 1][j] * i % mod[j];
}

ll FastPowMod(ll a, ll b, ll p){
    ll res = 1;

    while(b){
        if(b & 1) res = res * a % p;
        a = a * a % p;
        b >>= 1;
    }

    return res;
}

ll Lucas(ll n, ll k, ll p, int id){

    ll res = 1;

    while(n && k){
        ll a = n % p, b = k % p;
        if(a < b) return 0;
        res = res * fac[a][id] * FastPowMod(fac[b][id] * fac[a - b][id] % p, p - 2, p) % p;/**乘法逆元*/
        n /= p;
        k /= p;
    }

    return res;
}

void cal(ll x){
    for(int i = 0; i < 4; ++i)  left[i] = (left[i] + Lucas(n, x, mod[i], i)) % mod[i];/**C(n, d) % mod[i]*/
}

void extend_gcd(ll a, ll b, ll &x, ll &y){
    if(b == 0){
        x = 1;
        y = 0;
        return;
    }
    extend_gcd(b, a % b, y, x);
    y -= a / b * x;
}

ll CRT(){/**中国剩余定理*/
    ll res = 0, x, y;
    ll M = p - 1;

    for(int i = 0; i < 4; ++i){
        extend_gcd(M / mod[i], mod[i], x, y);
        res = ((res + x *  M / mod[i] * left[i]) % M + M) % M;
    }

    return res;
}

int main(){

    memset(left, 0, sizeof left);
    getFac();

    cin >> n >> g;

    if(g % p == 0) cout << "0" << endl;
    else{
        for(ll i = 1; i * i <= n; ++i){
            if(n % i) continue;
            cal(i);
            if(i * i != n) cal(n / i);
        }

        ll up = CRT();
        cout << FastPowMod(g % p, up, p) << endl;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值