给定n组整数(a,b),计算组合数C(a,b)的值。如C(3,1)=3,C(4,2)=6。
第一行为一个整数n,表示有多少组测试数据。(n <= 100000) 第2-n+1行,每行两个整数分别代表a,b;中间用空格隔开。(a,b <= 40)
对于每组输入,输出其组合数的值。每个输出占一行。
Input
4
3 1
4 2
5 0
1 1
3
6
1
1
long long 直接开15次左右阶乘就会爆,double 会出现精度问题
C(n,m)=n!/((n-m)!*m!)(m≤n)
#include<bits/stdc++.h>
using namespace std;
void C(int a,int b)//4 2
{
long long int res = 1;
//long long int x =1,y =1;
if(a == b || b == 0)res = 1;
else if(a < b)res = 0;//最容易遗漏,因此wa了好几次
else if(b == 1 || a-b == 1)res = a;
else
{
int j =1;
for(int i = a-b+1; i <= a; i++)//接都是阶乘,时间浪费,这里折中一下
{
res *= i;
if(res%j == 0 || j <= b)
{
res /= j;
j++;
}
}
// cout<<x<<" "<<y<<endl;
// res = x;
}
cout<<res<<endl;
// cout<<res<<endl;
}
int main()
{
int n;
cin>>n;
int a,b;
while(n--)
{
cin>>a>>b;
C(a,b);
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有