UVA 10375 Choose and divide 计算组合数C(p,q)/C(r,s)。

题目链接http://www.bnuoj.com/v3/problem_show.php?pid=18793


The binomial coefficient  C(m,n) is defined as
         m!
C(m,n) = --------
         n!(m-n)!
Given four natural numbers  pqr, and  s, compute the the result of dividing  C(p,q) by  C(r,s).

The Input

Input consists of a sequence of lines. Each line contains four non-negative integer numbers giving values for  pqr, 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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值