模数为素数时,根据费马小定理论用快速幂求
#include <stdio.h>
#include <iostream>
using namespace std;
const int MOD=998244353;
const int MAXN=202020;
int fac[MAXN],facinv[MAXN];
long long quickmul(int a,int b)
{
long long ret=1;
for(; b ; b >>=1 ,a =(long long) a * a % MOD)
if((b & 1))
ret=ret * a % MOD;
return ret;
}
long long C(int n,int m)
{
if(n<0||m<0||n<m)
return 0;
return (long long)fac[n]*facinv[m]%MOD*facinv[n-m]%MOD;
}
void init()
{
fac[0]=1;
for(int i=1;i<=MAXN;i++)
fac[i]=(long long)fac[i-1]*i%MOD;
facinv[MAXN]=quickmul(fac[MAXN],MOD-2);
for(int i=MAXN;i>0;i--)
facinv[i-1]=(long long)facinv[i]*(i)%MOD;
//1/(i-1)!=i/(i)!
}
int main()
{
init();
int n,m;
while(1)
{
scanf("%d %d",&n,&m);
printf("%lld\n",C(n,m));
}
}
模数不为逆元,根据杨辉三角
#include <bits/stdc++.h>
using namespace std;
int C[2000+5][2000+5];
void getC()
{
for( int i=1; i<=2000; i++ )
{
C[i][0] = C[i][i] = 1; //初始化第一列和对角线位置全为1,即最两边的位置
for( int j=1; j<i; j++ )
C[i][j] = (C[i-1][j] + C[i-1][j-1]) % 1007;
}
}
int main()
{
int m, n;
getC();
while(scanf("%d %d",&n,&m))
{
printf("%d\n", C[n][m] ); //第n行第m列即为从n中选m个
}
return 0;
}