《算法笔记》5.8小节——数学问题->组合数

这篇博客探讨了如何计算组合数,包括两个问题:计算阶乘和求解组合数。对于问题A,需要编写程序计算m! / (n! * (m-n)!),而问题B提醒我们在处理组合数时要注意语言的数宇类型限制和中间结果溢出。样例输入和输出提供了具体的示例来说明问题的解决方法。

目录

问题 A: 计算组合数

问题 B: 求组合数


问题 A: 计算组合数

题目描述

编制程序,输入m,n(M>=n>=0)后,计算下列表达式的值并输出:

         m!         

n! (m-n)!

要求将计算阶乘运算的函数写为fact(n),函数返回值的类型为float

输入

m n

输出

对应表达式的值

样例输入

2 1

样例输出

2

题解

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
double fact(int m, int n){
	double ans = 1;
	int i;
	for(i = 1; i <= n; i++){
		ans = ans * (m - n + i) / i;
	}
	return ans;
}
int main(){
	int m, n;
	while(scanf("%d%d", &m, &n) != EOF){
		double ans = fact(m, n);
		printf("%.0f\n", ans);
	}
}

问题 B: 求组合数

题目描述

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

输入

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

输出

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

样例输入

5 2
18 13

样例输出

10
8568

题解

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
double fact(int m, int n){
	double ans = 1;
	int i;
	for(i = 1; i <= n; i++){
		ans = ans * (m - n + i) / i;
	}
	return ans;
}
int main(){
	int m, n;
	while(scanf("%d%d", &m, &n) != EOF){
		double ans = fact(m, n);
		printf("%.0f\n", ans);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值