1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include<bits/stdc++.h> using namespace std; typedef long long LL; const LL N=1e5+9; LL A[N],M[N]; LL ksm(LL x,LL n,LL mod) { LL ans=1; while(n){ if(n&1)ans=ans*x%mod; n>>=1,x=x*x%mod; } return ans; } void exgcd(LL a,LL b,LL &x,LL &y) { if(!b)x=1,y=0; else exgcd(b,a%b,y,x),y-=a/b*x; } LL inv(LL a,LL p) { LL x,y; exgcd(a,p,x,y); return (x+p)%p?x:x+p; } LL get(LL n,LL pi,LL p) { if(!n)return 1; LL ans=1; if(n/p){ for(LL i=2;i<=p;++i)if(i%pi)ans=ans*i%p; ans=ksm(ans,n/p,p); } for(LL i=2;i<=n%p;++i)if(i%pi)ans=ans*i%p; return ans*get(n/pi,pi,p)%p; } LL exlucas(LL n,LL m,LL pi,LL p) { LL nn=get(n,pi,p); LL mm=get(m,pi,p); LL nm=get(n-m,pi,p); LL k=0; for(LL i=n;i;i/=pi)k+=i/pi; for(LL i=m;i;i/=pi)k-=i/pi; for(LL i=n-m;i;i/=pi)k-=i/pi; return nn*inv(mm,p)*inv(nm,p)*ksm(pi,k,p)%p; } LL crt(LL len,LL Lcm) { LL ans=0; for(LL i=1;i<=len;++i){ LL Mi=Lcm/M[i]; ans=((ans+A[i]*inv(Mi,M[i])*Mi)%Lcm+Lcm)%Lcm; } return ans; } int main() { ios::sync_with_stdio(false); LL n,m,P,num; while(cin>>n>>m>>P){ if(n<m){ cout<<0<<endl; continue; } num=0; memset(A,0,sizeof(A)); memset(M,0,sizeof(M)); for(LL x=P,i=2;i<=P;++i) if(x%i==0){ M[++num]=1; while(x%i==0){ M[num]*=i; x/=i; } A[num]=exlucas(n,m,i,M[num])%P; } cout<<crt(num,P)<<endl; } return 0; }
|