Binomial Showdown C(n,m)

/*Binomial Showdown Time Limit: 1000MS  Memory Limit: 65536K Total Submissions: 15798  Accepted: 4839

Description

In how many ways can you choose k elements out of n elements, not taking order into account? Write a program to compute this number. Input

The input will contain one or more test cases. Each test case consists of one line containing two integers n (n>=1) and k (0<=k<=n). Input is terminated by two zeroes for n and k. Output

For each test case, print one line containing the required number. This number will always fit into an integer, i.e. it will be less than 231. Warning: Don't underestimate the problem. The result will fit into an integer - but if all intermediate results arising during the computation will also fit into an integer depends on your algorithm. The test cases will go to the limit.

Sample Input

4 2 10 5 49 6 0 0

Sample Output

6 252 13983816

*/

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
 int n,k,i;
 __int64 sum;
 while(scanf("%d%d",&n,&k),k||n)
 {
  sum=1;
  if(k>n/2)
   k=n-k;
  if(k==0)
  {
   printf("%d\n",sum);
   continue;
  }
  for(i=0;i<k;i++)
  {
   sum*=n-i;//虽然最后结果是在int范围内,但此时中间的sum可能会在最后一下相乘的情况下超过,所以用__int64
   sum/=i+1;
  }
  printf("%I64d\n",sum);
 }
 return 0;
}

 

或者别人的代码

#include <iostream>  
  
using namespace std;  
 
int main()  
{  
    int m,n;  
   while (cin>>m>>n,m||n)  
    {  
       double result = 1;  
       if(n>m/2)  
           n=m-n;  
        if(n==0)  
     {  
           cout<<"1"<<endl;  
            continue;  
        }  
        for (int i = 0;i < n;i++)  
        {  
          result*=(m-i);  
            result/=(n-i);  
        }  
        printf("%.0lf\n",result);  
   }  
   return 0;
}  

 

 排列组合递归调用

#include<stdio.h>

#include<iostream>

#include<algorithm>

#include<cmath>

using namespace std;

int C(int n,int m)

{    

if(n==m||m==0) return 1;

 if(m==1||m==n-1) return n;

 return C(n-1,m-1)+C(n-1,m);

}

int main()

{  

int n,m;

 while(scanf("%d%d",&n,&m)!=EOF)  

 printf("%d\n",C(n,m));

 return 0;

}

 

posted @ 2012-07-25 10:04  myth_HG  阅读(979)  评论(0编辑  收藏  举报