题面:
Choose and divide
The binomial coefficient C(m; n) is defined as C(m; n) =m!/(m -n)! n! Given four natural numbers p, q, r, and s, compute the the result of dividing C(p; q) by C(r; s).
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.
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
Sample Output
0.12587
505606.46055
1.28223
0.48996
2.00000
3.99960
题意:
设C(m,n) = m! / ((m - n)! * n!),输入正整数p、q、r、s,输出C(p,q)/C(r,s)。
因为结果为小数,看着好像可以直接算,但是直接算会有两个问题。一,会爆数据范围,二,一边乘一边除会造成严重的精度丢失。
定理:
【 唯一分解定理 】
任何一个大于1的自然数N,如果N不为质数,那么N可以唯一分解成有限个质数的乘积N=P1a1P2a2P3a3......Pnan,这里P1<P2<P3......<Pn均为质数,其中指数ai是正整数。这样的分解称为N的标准分解式。
结合以上定理,我们可以开一个数组,记录每个因子的个数,乘的加,除的减。并且在原式上可以做一点点优化,可以转换为(q+1)*(q+2)*.......(p-1)*p*(r-s)!/((p-q)!*(s+1)*(s+2)*......(r-1)*r)。因为,分解占用比较多时间,但对于非素数,分解还是比较快的,用时880ms。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int num[100010];
void cal(int x,bool flag)
{
int ix=2;
if(flag)
{
while(x>1)
{
while(x%ix==0)
{
num[ix]++;
x/=ix;
}
ix++;
}
}
else
{
while(x>1&&x>=ix)
{
while(x%ix==0)
{
num[ix]--;
x/=ix;
}
ix++;
}
}
}
int main()
{
int p,q,r,s;
double ans;
while(~scanf("%d%d%d%d",&p,&q,&r,&s))
{
ans=1.0;
memset(num,0,sizeof(num));
for(int i=q+1;i<=p;i++)
cal(i,1);
for(int i=1;i<=(p-q);i++)
cal(i,0);
for(int i=1;i<=(r-s);i++)
cal(i,1);
for(int i=s+1;i<=r;i++)
cal(i,0);
for(int i=1;i<=100000;i++)
{
if(num[i]>0)
ans*=pow(1.0*i,num[i]);
else
ans/=pow(1.0*i,-num[i]);
}
printf("%.5lf\n",ans);
}
return 0;
}
优化:
因为数据范围只到100000,我们可以预先判断是不是素数,是素数就不必进行分解了。优化之后,840ms(好弱的优化)。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int num[100010];
bool is_prime[100010];
void init()
{
memset(is_prime,-1,sizeof(is_prime));
for(int i=2;i<=100000;i++)
if(is_prime[i])
for(int j=2*i;j<=100000;j+=i)
is_prime[j]=0;
}
void cal(int x,int flag)
{
int ix=2;
while(x>1)
{
while(x%ix==0)
{
num[ix]+=flag;
x/=ix;
}
ix++;
}
}
int main()
{
int p,q,r,s;
double ans;
while(~scanf("%d%d%d%d",&p,&q,&r,&s))
{
ans=1.0;
memset(num,0,sizeof(num));
for(int i=q+1;i<=p;i++)
if(is_prime[i])
num[i]++;
else
cal(i,1);
for(int i=1;i<=(p-q);i++)
if(is_prime[i])
num[i]--;
else
cal(i,-1);
for(int i=1;i<=(r-s);i++)
if(is_prime[i])
num[i]++;
else
cal(i,1);
for(int i=s+1;i<=r;i++)
if(is_prime[i])
num[i]--;
else
cal(i,-1);
for(int i=1;i<=100000;i++)
{
if(num[i]>0)
ans*=pow(1.0*i,num[i]);
else
ans/=pow(1.0*i,-num[i]);
}
printf("%.5lf\n",ans);
}
return 0;
}