需要分情况讨论。
然后求组合数 套上lucas。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n, k, p;
ll powmod(ll a, ll b){ ll res = 1; a %= p; while(b){ if(b&1) res = res*a%p; b>>=1; a = a*a%p; } return res; }
ll fac[1310][10100];
bool is[100010];
int cnt;
int pr[10010];
int id[10010];
void init(){
cnt = 0;
for(int i=2; i<=10000; i++){
if(!is[i]){
pr[++cnt] = i;
id[i] = cnt;
for(int j=i+i; j<=10000; j+=i)
is[j] = true;
}
}
for(int i=1; i<=cnt; i++){
fac[i][0] = 1;
for(int j=1; j<=10000; j++){
fac[i][j] = fac[i][j-1] * j % pr[i];
}
}
}
ll getc(int n, int m, ll p, int tmp){
if(m > n) return 0;
ll res = fac[tmp][n]*powmod(fac[tmp][n-m]*fac[tmp][m]%p, p-2)%p;
return res;
}
ll lucas(int n, int m, ll p, int tmp){
if(m == 0) return 1;
return lucas(n/p, m/p, p, tmp)*getc(n%p, m%p, p, tmp)%p;
}
int main(){
int icase = 0;
init();
while(~scanf("%lld %lld %lld", &n, &k, &p)){
int tmp = id[p];
if(k > n/2) k = n- k;
ll res = lucas(n+1, k, p, tmp);
printf("Case #%d: %lld\n", ++icase, (res + n - k)%p);
}
return 0;
}