Power OJ Alice的编程之旅(组合数,费马小定理)

传送门

打一遍阶乘表,后面计算的时候就可以直接用了,否则会超时,还有这道题不能用cin,cout也会导致超时。由于p是质素,我们就可以用费马小定理和快速幂求出逆元然后根据公式就可以求出答案了

#include<bits/stdc++.h>
#define lson l, mid, root << 1
#define rson mid + 1, r, root << 1 | 1
#define father  l , r , root
#define lowbit(x) ( x & ( - x ) )
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
const int inf = 0x3f3f3f3f;
ll jc[maxn];
void chart(){
    
    
	jc[0]=1;
	for(int i=1;i<=1e5;i++){
    
    
		jc[i]=jc[i-1]*i%mod;
	} 
}
ll quick_pow(ll n,ll k){
    
    
	ll ans=1;
	while(k){
    
    
		if(k&1){
    
    
			ans=ans*n%mod;
		}
		n=n*n%mod;
		k>>=1;
	}
	return ans;
}
ll C(ll n,ll m){
    
    
	if(n<=0)return 0;
	if(n<m)return 0;
	if(n==m)return 1;
	if(m>n-m)m=n-m;
	ll x=jc[m]*jc[n-m]%mod;
	ll ans=jc[n]*quick_pow(x,mod-2);
	return ans%mod;
} 
int main( ){
    
    
    chart();
    int t;
    scanf("%d",&t);
    while(t--){
    
    
    	ll n,m;
    	scanf("%lld%lld",&n,&m);
		printf("%lld\n",C(n,m)); 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43715171/article/details/97760220