/********************************/
/* This program is used to */
/* calculate C(N,R) */
/* */
/* */
/* First input is N , */
/* and second 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("%d things taken %d at a time is %0.Lf exactly.\n",N,R,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
{
for(int i=1 ; i<=r ; i++)
{
tempres = (tempres * (n-r+i) / i) ;
}
return tempres;
}
}
本來我用遞迴做
馬上就被賞了個TLE
還是乖乖的邊乘邊除
No comments:
Post a Comment