HDU-5446 Unknown Treasure(中国剩余定理+卢卡斯定理)

题意

输出 Cmn%i=1ppi C n m % ∏ i = 1 p p i 的值。
1n,m1018 1 ≤ n , m ≤ 10 18
1k10 1 ≤ k ≤ 10
i=1ppi1018 ∏ i = 1 p p i ≤ 10 18 1pi105 1 ≤ p i ≤ 10 5

思路

Lucas L u c a s 定理与 CRT C R T 结合的模板题,其中分成小质数分别取模合并出大数的模,这种方法值得借鉴。
Lucas L u c a s 定理内容:
对于质数 P P ,有 CnmCn/Pm/P×Cn%Pm%P(modP)
证明:
n/P=s,m/P=t,n%P=u,m%P=v n / P = s , m / P = t , n % P = u , m % P = v
则原题化为 CmnCts×Cvu(modm) C n m ≡ C s t × C u v ( mod m )
构造二项式 (1+x)n ( 1 + x ) n
(1+x)n ( 1 + x ) n
(1+x)sP+u ≡ ( 1 + x ) s P + u
((1+x)P)s×(1+x)u ≡ ( ( 1 + x ) P ) s × ( 1 + x ) u
(1+x)s×(1+x)u ≡ ( 1 + x ) s × ( 1 + x ) u (费马小定理)
(1+xP)s×(1+x)u ≡ ( 1 + x P ) s × ( 1 + x ) u ② (modP) ( mod P )
而幂为 m m 那一项的系数①项中是 Cnm ,②项中是 Cts×Cvu C s t × C u v
两者相等,得证。

代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
typedef long long LL;
using namespace std;
LL fac[100003],invfac[100003];

struct CRT
{
    LL A,P;
    LL gcd(LL a,LL b){return b?gcd(b,a%b):a;}
    void exgcd(LL a,LL b,LL &x,LL &y)
    {
        if(!b){x=1,y=0;return;}
        exgcd(b,a%b,y,x);y-=a/b*x;
        return;
    }
    LL Exgcd(LL A,LL B,LL C)
    {
        LL k1,k2,g=gcd(A,B);
        A/=g,B/=g,C/=g;
        exgcd(A,B,k1,k2);
        return (k1*C%B+B)%B;
    }
    void kase_insert(CRT _)
    {
        LL res=Exgcd(P,_.P,_.A-A);
        A+=res*P;
        P=P/gcd(P,_.P)*_.P;
        return;
    }
};

LL Pow(LL a,LL p,LL P)
{
    LL res=1;
    while(p)
    {
        if(p&1)(res*=a)%=P;
        (a*=a)%=P;
        p>>=1;
    }
    return res;
}
void init(LL P)
{
    LL f=1;
    FOR(i,0,P-1)
    {
        fac[i]=f;
        (f*=i+1)%=P;
    }
    invfac[P-1]=Pow(fac[P-1],P-2,P);
    DOR(i,P-2,0)invfac[i]=invfac[i+1]*(i+1)%P;
    return;
}
LL C(LL n,LL m,LL P){return n<m?0:fac[n]*invfac[n-m]%P*invfac[m]%P;}
LL Lucas(LL n,LL m,LL P){return m?Lucas(n/P,m/P,P)*C(n%P,m%P,P)%P:1;}

int main()
{
    int T,k;LL n,m,P;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld%d",&n,&m,&k);
        CRT sum;
        FOR(i,1,k)
        {
            scanf("%lld",&P);
            init(P);
            if(i==1)sum=(CRT){Lucas(n,m,P),P};
            else sum.kase_insert((CRT){Lucas(n,m,P),P});
        }
        printf("%lld\n",sum.A);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值