Problem Description
Eddy’s company publishes a kind of lottery.This set of lottery which are numbered 1 to n, and a set of one of each is required for a prize .With one number per lottery, how many lottery on average are required to make a complete set of n coupons?
Input
Input consists of a sequence of lines each containing a single positive integer n, 1<=n<=22, giving the size of the set of coupons.
Output
For each input line, output the average number of lottery required to collect the complete set of n coupons. If the answer is an integer number, output the number. If the answer is not integer, then output the integer part of the answer followed by a space and then by the proper fraction in the format shown below. The fractional part should be irreducible. There should be no trailing spaces in any line of ouput.
Sample Input
2
5
17
Sample Output
3
5
11 –
12
340463
58 ------
720720
就是求n*(1+1/2+1/3+1/4+…1/n)
#include<stdio.h>
long long gcd(long long a,long long b)
{ //求最大公因数
long long r;
while(b>0)
{
r=a%b;
a=b;
b=r;
}
return a;
}
long long getlen(long long x)
{ //求数字x的长度
long long len=0;
while(x){
len++;
x=x/10;
}
return len;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF) //就是因为没加EOF,一直时间超限,找了好长时间
{
long long x=0,y=1;
for(int i=1;i<=n;i++)
{
x=y+i*x;
y*=i;
long long GCD=gcd(x,y);
x=x/GCD;
y=y/GCD;
}
long long GCD=gcd(n,y);
y/=GCD;
n/=GCD;
x*=n;
if(x%y==0) printf("%lld\n",x/y);
else
{ //注意输出格式,按行输出
long long q=x/y;
long long b=getlen(q);
for(long long i=0;i<=b;i++)
printf(" ");
printf("%lld\n",x%y);
if(x>y) printf("%lld ",q);
long long a=getlen(y);
for(long long i=0;i<a;i++)
printf("-");
printf("\n");
for(long long i=0;i<=b;i++)
printf(" ");
printf("%lld\n",y);
}
}
return 0;
}