作者tw00088437 (喵猫 loves fish)
看板C_and_CPP
标题[语法] 自己写的计算Cn取m 在奇怪的地方会出错
时间Sat Nov 7 19:33:52 2009
要求是输入n,m 输出Cn取m(组合) 且答案在long long的范围内
我是写了三个函式
第一个(common)先找出最大公因数
第二个(meowth)利用common把(n-m+1)/m化简为最简分数
然後正式计算的第三个函式CNM用recursion
( C(n,m)=C(n,m-1)*(n-m+1)/m)
因为先把n-m+1和m化简过了 所以先除在乘 既不会爆也不会有小数
对於大部分的数都成功了
例如
100 things taken 6 at a time is 1192052400 exactly.
18 things taken 6 at a time is 18564 exactly.
可是像
20 things taken 5 at a time is 48 exactly.
(正确应该是15504)
出来就是错的
不知道为什麽会有些对有些错@@
或许是我pass by reference用的不熟?
code如下#include<iostream>
using namespace std;
unsigned long long c,d;
void meowth(int *,int *);
int common(int,int);
long long CNM(int,int);
int main()
{
while(cin>>c>>d)
{
if(c==0&&d==0)
break;
cout<<c<<" things taken "<<d<<" at a time is "<<CNM(c,d)<<"
exactly."<<endl;
}
return 0;
}
void meowth(int * a,int *b)
{
int e=common(*a,*b);
*a/=e;
*b/=e;
}
int common(int c,int d)
{
while((c%=d) && (d%=c));
return c+d;
}
long long CNM(int e,int f)
{
if(f<=e/2)
{
if(f==0)
return 1;
else
{
int x=e-f+1;
meowth(&x,&f);
return (CNM(e,f-1)/f*x);
}
}
else
{
if(f==e)
return 1;
else
{
int y=f+1;
int z=e-f;
meowth(&y,&z);
return (CNM(e,f+1)/z*y);
}
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.228.104.180
1F:→ hilorrk:Cn取m不就是n!/(m!*(n-m)!)吗XD 11/07 20:56
2F:→ bleed1979:也许可以考虑用阵列做,比较不会出错 11/07 21:12
3F:→ tw00088437:可是阵列要怎麽define大小呢 事先没有给范围... 11/07 21:17
4F:→ tw00088437:另外请教一下可能的错误原因是@@? 11/07 21:17
5F:→ bleed1979:C(5,3)=C(5,2)*3/3 10先除3再乘上3会不对 整数除法 11/07 21:24
6F:→ tw00088437:可是我在return前面都有先meowth(化简)@@ 11/07 21:26
7F:→ tw00088437:像(3,3)理论上就会被化简成(1,1)@@? 11/07 21:26
8F:→ tw00088437:而且像我的C5取3坐出来的确是对的@@" 11/07 21:32
9F:推 walker2009:看来原po最近UVa题目也冲很大XD 11/08 01:57
10F:→ tw00088437:0_o 11/08 14:03