GDUT-寒假专题训练4--Combinations

题目:

Computing the exact number of ways that N things can be taken M at a time can be a great challenge when N and/or M become very large. Challenges are the stuff of contests. Therefore, you are to make just such a computation given the following:
GIVEN: 5 <= N <= 100; 5 <= M <= 100; M <= N
Compute the EXACT value of: C = N! / (N-M)!M!
You may assume that the final value of C will fit in a 32-bit Pascal LongInt or a C long. For the record, the exact value of 100! is:
93,326,215,443,944,152,681,699,238,856,266,700,490,715,968,264,381,621, 468,592,963,895,217,599,993,229,915,608,941,463,976,156,518,286,253, 697,920,827,223,758,251,185,210,916,864,000,000,000,000,000,000,000,000

Input

The input to this program will be one or more lines each containing zero or more leading spaces, a value for N, one or more spaces, and a value for M. The last line of the input file will contain a dummy N, M pair with both values equal to zero. Your program should terminate when this line is read.

Output

The output from this program should be in the form:
N things taken M at a time is C exactly.

Sample

InputcopyOutputcopy
100  6
20  5
18  6
0  0
100 things taken 6 at a time is 1192052400 exactly.
20 things taken 5 at a time is 15504 exactly.
18 things taken 6 at a time is 18564 exactly.

题意:这题其实就是要算出c(n,m)

题解:这题直接算的话数组会不够大,但是其实只要将所有的数都用他们的因数相乘表示,然后将分子分母的相同因数约掉即可。

#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <cstdio>

using namespace std;
	int c[101],d[101];
inline void check(int a)
{
	if (a==1) return;
	for (int i=2;i<=a;i++)
	  if (a%i==0) {c[i]++;check(a/i);break;}//不断用最小因数相乘表示
}

inline void checkk(int a)
{
	  if (a==1) return;
	for (int i=2;i<=a;i++)
	 if (a%i==0) {d[i]++;checkk(a/i);break;}//不断用最小因数相乘表示
}
int main()
{
	int n,m;
	while(cin >> n >>m)
	{
		if (n==0&&m==0) break;
		for (int i=1;i<=100;i++)
		 { c[i]=0;d[i]=0;}	 
		long long f=1;
		for (int i=2;i<=n;i++)//分子是n!
		 check(i);
		for (int i=2;i<=n-m;i++) //分母其中之一是(n-m)!
		 checkk(i);
		for (int i=2;i<=m;i++)//另外一个分母是m!
		 checkk(i);
		for (int i=1;i<=100;i++)
		 if (c[i]!=0&&d[i]!=0) {int g=c[i];c[i]=c[i]-min(c[i],d[i]);d[i]=d[i]-min(g,d[i]);}//约掉所有可以约掉的因子
		for (int i=2;i<=97;i++)
		{
			  for (int j=1;j<=c[i];j++) f=f*i;//算出不能约掉的分子乘积和
			 
		} 
		for (int i=100;i>=2;i--)
		  for (int j=1;j<=d[i];j++) f=f/i;//除去不能约掉的分母
		cout << n << " things taken " << m << " at a time is " << f <<" exactly." << endl;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值