在书上看到这题,又把期望的概念复习了一遍,然后推了半天公式,结果就是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;
}