[語法] 自己寫的計算Cn取m 在奇怪的地方會出錯

看板C_and_CPP作者 (喵貓 loves fish)時間16年前 (2009/11/07 19:33), 編輯推噓1(109)
留言10則, 4人參與, 最新討論串1/2 (看更多)
要求是輸入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

11/07 20:56, , 1F
Cn取m不就是n!/(m!*(n-m)!)嗎XD
11/07 20:56, 1F

11/07 21:12, , 2F
也許可以考慮用陣列做,比較不會出錯
11/07 21:12, 2F

11/07 21:17, , 3F
可是陣列要怎麼define大小呢 事先沒有給範圍...
11/07 21:17, 3F

11/07 21:17, , 4F
另外請教一下可能的錯誤原因是@@?
11/07 21:17, 4F

11/07 21:24, , 5F
C(5,3)=C(5,2)*3/3 10先除3再乘上3會不對 整數除法
11/07 21:24, 5F

11/07 21:26, , 6F
可是我在return前面都有先meowth(化簡)@@
11/07 21:26, 6F

11/07 21:26, , 7F
像(3,3)理論上就會被化簡成(1,1)@@?
11/07 21:26, 7F

11/07 21:32, , 8F
而且像我的C5取3坐出來的確是對的@@"
11/07 21:32, 8F

11/08 01:57, , 9F
看來原po最近UVa題目也衝很大XD
11/08 01:57, 9F

11/08 14:03, , 10F
0_o
11/08 14:03, 10F
文章代碼(AID): #1AzLiaXj (C_and_CPP)
文章代碼(AID): #1AzLiaXj (C_and_CPP)