Coupons
Input: standard input
Output: standard output
Time Limit: 2 seconds
Memory Limit: 32 MB
Coupons in cereal boxes are numbered 1 to n, and a set of one of each is required for a prize (a cereal box, of course). With one coupon per box, how many boxes 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<=33, giving the size of the set of coupons. Input is terminated by end of file.
Output
For each input line, output the average number of boxes 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 output.
Sample Input
2
5
17
Sample Output
3
5
11 --
12
340463
58 ------
720720
题目不难
最后答案为 n*Zegma(1,n) 1/i
每次相加都要进行及时的约分避免溢出!
输出很蛋疼!#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <string> #include <algorithm> #include <queue> using namespace std; typedef long long LL; int n; LL gcd(LL a,LL b){ if(b==0) return a; return gcd(b,a%b); } struct fraction{ LL rator,deno; fraction(LL rator=0,LL deno=0):rator(rator),deno(deno){} friend fraction operator + (fraction a,fraction b){ LL t1 = a.rator*b.deno+a.deno*b.rator,t2 = a.deno*b.deno; LL g = gcd(t1,t2); return fraction(t1/g,t2/g); } }; int getlen(LL a){ int len = 0; while(a){ a/=10; len++; } return len; } int main(){ while(~scanf("%d",&n)){ fraction ans=fraction(1,1); for(int i = 2; i <= n; i++){ ans = fraction(1,i)+ ans; } LL t = gcd(ans.deno,n); ans.deno /= t; ans.rator *= n/t; LL d = ans.rator/ans.deno,k = ans.rator%ans.deno; if(k!=0){ int lr = getlen(d),lk = getlen(k),ld = getlen(ans.deno); for(int i = 0; i <= lr; i++) cout<<" "; cout<<k<<endl; cout<<d<<" "; for(int i = 0; i < ld; i++) cout<<"-"; cout<<endl; for(int i = 0; i <= lr; i++) cout<<" "; cout<<ans.deno<<endl; }else{ cout<<d<<endl; } } return 0; }