Combinations
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 10081 | Accepted: 4614 |
Description
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 Input
100 6 20 5 18 6 0 0
Sample Output
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)=C(n-1,m-1)+C(n-1,m)
C(n,m)=n!/[m!(n-m)!]
代码一会儿下完了,真的写完了。都是bug,调试了很长时间
#include<string.h>
#include<stdio.h>
#include<algorithm>
#define N 130
int main()
{
int i,j,k,m,n,ansLen,count,tempMul,tempJ,lastSum;
int mulArray[N],ans[N];
scanf("%d%d",&n,&m);
memset(ans,0,sizeof(ans));
for(i=m+1; i<=n; i++)
mulArray[i] = i;
/*for(j=2; j<=n-m; j++){//漏掉了后面不能整除的大的数字
for(i=m+1; i<=n; i++){
if(mulArray[i] % j == 0)
{
mulArray[i] = mulArray[i] / j;
break;
}
}
}*/
for(j=2; j<=n-m; j++){
tempJ = j;
for(i=m+1; i<=n; i++){//不知道j和mulArray[i]哪一个更大
if(mulArray[i] != 1 && tempJ != 1)//除公因数
{
count = 1;
while(count > 0){
count = 0;
for(k=2; k<=tempJ && k<=mulArray[i]; k++)
if(tempJ % k == 0 && mulArray[i] % k == 0){
tempJ /= k;
count++;
mulArray[i] /= k;
}
}
}
}
/*if(i>n){//还是除不尽
tempJ = j;
for(i=m+1; i<=n; i++)
if((mulArray[i] != 1) && (tempJ % mulArray[i] == 0)){
tempJ = tempJ / mulArray[i];
mulArray[i] = 1;
}
}*/
}
ans[0] = 1;
ansLen = 1;
for(j=m+1; j<=n; j++){//在这区间进行叠乘
lastSum = 0;//lastSum是低位向高位截取过后的
for(i=0; i<ansLen; i++){//每一位进行计算
tempMul = ans[i] * mulArray[j] + lastSum;
ans[i] = tempMul % 10;
lastSum = tempMul / 10;//lastSum可能好几位
}
while(lastSum != 0){//多少位就进多少位
ans[ansLen] = lastSum % 10;
lastSum = lastSum / 10;
ansLen++;
}
}
for(i=ansLen-1; i>=0; i--)
printf("%d",ans[i]);
printf("\n");
return 0;
}
惨痛的调试过程:深刻诠释了什么叫做眼高手低
即使在外面嵌套了一个循环依然没有按照要求整除数据
比如:tempJ 变成3,而mulArray最小的也比它大,这样不可能整除的。
最后考虑两者共有的除数(好像不是怎么叫的),然后外层加一个计数器,当本轮没有整除的时候就跳出循环。
记录一下吧。