排列组合 求从n个数中选出m个的组合数,不分先后,不需用大数来做,而是把分子分母分别保存在两个数组p、q中,然后依次把分母的元素与分子相除,最终所有分母都为一,这时把分子数组元素依次相乘便得到结果;
#include<iostream> using namespace std; int gcd(int m,int n) { if(m%n==0) return n; else return gcd(n,m%n); } int main() { int n,k,i,j; while(cin>>n>>k) { if(n==0&&k==0) break; if(k>n-k) k=n-k; int *p=new int[k+1]; int *q=new int[k+1]; int temp=n; for(i=1;i<=k;i++) { p[i]=temp--; q[i]=i; } for(i=1;i<=k;i++) { while(1) { if(q[i]==1) break; else { for(j=1;j<=k;j++) { int g=gcd(p[j],q[i]); if(g!=1) { p[j]/=g; q[i]/=g; if(q[i]==1) break; } } } } } int sum=1; for(i=1;i<=k;i++) sum*=p[i]; cout<<sum<<endl; } return 0; }