在书上看到这题,又把期望的概念复习了一遍,然后推了半天公式,结果就是n*Sigma(1/i),运算过程注意约分,可能会超int64。
ACcode:
#include<cstdio>
#include<cstring>
#include<cmath>
typedef long long LL;
LL gcd(LL aa,LL bb)
{
return bb==0?aa:gcd(bb,aa%bb);
}
int main()
{
int n;
int sum;
LL p,q,s,t,m;
while (~scanf("%d",&n))
{
p=q=1;
sum=0;
for (int i=2;i<=n;i++)
{
s=p/gcd(p,i)*i;
q=s/p*q+s/i;
p=s;
// printf("p=%I64d q=%I64d\n",p,q);
t=gcd(p,q);
p/=t,q/=t;
sum+=(int)(q/p);
q%=p;
}
sum*=n;
q*=(LL)n;
sum+=(int)(q/p);
q%=p;
t=gcd(p,q);
p/=t,q/=t;
s=(int)(log(p)/log(10)+1);
m=t=(int)(log(sum)/log(10)+2);
if (q==0)
printf("%d\n",sum);
else
{
while (t--) printf(" ");
printf("%lld\n",q);
printf("%d ",sum);
while (s--) printf("-");
printf("\n");
while (m--) printf(" ");
printf("%lld\n",p);
}
}
return 0;
}
本文介绍了一种计算调和级数期望值的方法,并通过C++代码实现了该算法。通过对调和级数的数学性质进行分析,文章提供了一个有效的解决方案来避免整型溢出问题。
851

被折叠的 条评论
为什么被折叠?



