Thursday, July 29, 2010

ACM-530 Binomial Showdown with C++


/********************************/
/* This program is used to      */
/*    calculate C(N,R)          */
/*                              */
/*                              */
/* First input is N ,and second */
/* one is R                     */
/* Output is the result of      */
/* C(N,R)                       */
/********************************/

#include <iostream>

using namespace std;
long double calculate(int n , int r);

int main(int argc, char* argv[])
{
 int N,R,temp;
 long double res;
 
 
 while(cin>>N>>R)
 {
  //the situation that stop the program
  if(N==0 && R==0)
  {
   break;
  }
  
  /****************************/
  /*  check                   */
  /*  if N!=R and R > N/2     */
  /*  then C(N,R) = C(N,N-R)  */
  /****************************/
  
  if(N != R && R > (N/2))
  {
   temp = N - R;
  }else
  {
   temp = R;
  }
  
  /* start to caiculate C(N,R) */
  res = calculate(N ,temp);
  printf("%0.Lf\n",res);
 }
 return 0;
}


long double calculate( int n , int r)
{
 long double tempres = 1.0;
 
 if(n == r)
 {
  return 1;
 }
 else if(r == 1)
 {
  return n;
 }
 else if(r ==0)
 {
  return 1;
 }
 else
 {
  for(int i=1 ; i<=r ; i++)
  {
   tempres = (tempres * (n-r+i) / i) ;
  }
  return tempres;
 }
}




幾乎和369是一樣的題目

除了一部分的條件不同

根本是寫一題賺兩題 = =a

No comments: