Codeup100000595问题 B: 求组合数

题目描述:

组合数的计算虽说简单但也不乏有些陷阱,这主要是因为语言中的数据类型在表示范围上是有限的。更何况还有中间结果溢出的现象,所以千万要小心。

输入:

求组合数的数据都是成对(M与N)出现的,每对整数M和N满足0<m, n≤20,以EOF结束。

输出:

输出该组合数。每个组合数换行。

样例输入:

5 2
18 13

样例输入:

10
8568

实现代码1(定义求解,范围小适用):

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <algorithm>
#include <math.h>
using namespace std;

float fact(int n){
	float ans=1;
	for(int i=1;i<=n;i++){
		ans=ans*i;
	}
	return ans;
} 

int main()
{
	int m,n;
	while(scanf("%d%d",&m,&n)!=EOF){
		printf("%.0f\n",fact(m)/fact(n)/fact(m-n));
	}
	return 0;
}

实现代码2(推荐):

#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <algorithm>
#include <math.h>
using namespace std;

long long C(long long m,long long n){
	if(n==m||n==0){
		return 1;
	}else{
		return C(m-1,n)+C(m-1,n-1);
	}
	
}

int main()
{
	int m,n;
	while(scanf("%d%d",&m,&n)!=EOF){
		printf("%d\n",C(m,n));
	}
	return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值