U: A Easy Problem
Description
This is a classical problem. Your job is to calculate the combination formula C(n,m) , and C(n,m) fit a 64-bit unsigned integer.(注意答案的范围)
Input
The first line of input there is one integer T(T≤100), giving the number of test cases in the input. Each test case contains a line with two integer n and m(0≤m≤n<264).
Output
For each case, output the answer C(n,m) corresponding to the input.
Sample Input
1
4 2
Sample Output
6
这个题目数据是蛮极限的,有点恐怖。
首先想到的是递推,用公式C(n,m)=C(n-1,m)+C(n-1,m-1).但是输入可能有2^63,那肯定就爆了啊
其次就直接先算分子,然后算分母,再除掉,但是想想就知道这样很容易爆掉
所以就先和我们实际算组合数一样写出分子分母,然后约分到分母全被约去,然后将分子乘起来就行
#include <cstdio>
#include <iostream>
#include <algorithm>
#define LL long long
#define ULL unsigned long long
#define mem(a,n) memset(a,n,sizeof(a))
#define fread freopen("in.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
#define N 10100
#define INF 0x3f3f3f3f
#define eps 1e-9
using namespace std;
ULL gcd(ULL a,ULL b){
return (b==0?a:gcd(b,a%b));
}
ULL nume[20000],demo[10000];
int main()
{
ULL a,b,c,t,cnt1,cnt2,i,j;
cin>>t;
while(t--){
cin>>a>>b;
c=1;
cnt1=cnt2=0;
if(a==b||b==0){
cout<<1<<endl;
continue;
}
if(b==a-1||b==1){
cout<<a<<endl;
continue;
}
b=min(b,a-b);
for(i=a-b+1;i<=a;++i){
nume[cnt1++]=i;
}
for(i=2;i<=b;++i){
demo[cnt2++]=i;
}
for(i=0;i<cnt2;++i){
for(j=0;demo[i]!=1&&j<cnt1;++j){
ULL n=gcd(demo[i],nume[j]);
demo[i]/=n;
nume[j]/=n;
}
}
for(int i=0;i<cnt1;++i){
c*=nume[i];
}
cout<<c<<endl;
}
return 0;
}