題目鏈接http://www.bnuoj.com/v3/problem_show.php?pid=18793
m! C(m,n) = -------- n!(m-n)!
The Input
Input consists of a sequence of lines. Each line contains four non-negative integer numbers giving values for p, q, r, and s, respectively, separated by a single space. All the numbers will be smaller than 10,000 with p>=q and r>=s.The Output
For each line of input, print a single line containing a real number with 5 digits of precision in the fraction, giving the number as described above. You may assume the result is not greater than 100,000,000.Sample Input
10 5 14 9 93 45 84 59 145 95 143 92 995 487 996 488 2000 1000 1999 999 9998 4999 9996 4998
Output for Sample Input
0.12587 505606.46055 1.28223 0.48996 2.00000 3.99960
下面給出兩種解法:
1.
分解每個乘數的質因子,然後利用 質因子的表示方法 去連乘,比如50=(2^1)*(5^2),可參考紫書317頁
//分解每個乘數的質因子,然後利用 質因子的表示方法 去連乘,比如50=(2^1)*(5^2)
#include<cmath>
#include<cstring>
#include<cstdio>
using namespace std;
const int MAX=10005;
int p,q,r,s,e[MAX]; //e存儲因子的個數
void add_factorial(int n,int d) //分解質因子
{
for(int i=2;i<MAX;i++){
while(n%i==0){
n/=i;
e[i]+=d;
}
if(n==1) break;
}
}
void solve()
{
memset(e,0,sizeof(e));
//...C(p,q)
for(int i=p;i>=p-q+1;i--) add_factorial(i,1);
for(int i=q;i>=1;i--) add_factorial(i,-1);
//...1/C(r,s)
for(int i=r;i>=r-s+1;i--) add_factorial(i,-1);
for(int i=s;i>=1;i--) add_factorial(i,1);
double ans=1;
for(int i=2;i<MAX;i++)
ans*=pow(i,e[i]);
printf("%.5lf\n",ans);
}
int main()
{
while(~scanf("%d%d%d%d",&p,&q,&r,&s))
{
solve();
}
return 0;
}
2.
//將組合數化簡一下邊乘邊除
#include<stdio.h>
int p,q,r,s;
void solve()
{
double ans = 1.0;
if(p-q<q) q=p-q; //因爲C(p,q)=C(p,p-q)
if(r-s<s) s=r-s; //同理
for(int i=1;i<=p||i<=r;i++){
if(i<=q) ans=ans*(p-i+1)/i;
if(i<=s) ans=ans/(r-i+1)*i;
}
printf("%.5lf\n", ans);
}
int main()
{
while(scanf("%d%d%d%d",&p,&q,&r,&s)==4)
solve();
return 0;
}