Uva 10288 Coupons
Description
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 \le n \le 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
若当前已有\(k\)种Coupons,那么获得新的Coupons的概率为\(p = \frac{n-k}{n}\),所以获得一种新Coupons的期望步数为$$p+2p(1-p)+3p(1-p)^2+\cdots$$
用错位相消+无穷等比数列求和数列公式,化简得\(\frac{n}{n-k}\),所以$$ans = n\sum_{i = 1}^{n}\frac{1}{i}$$
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef long long ll;
int N;
inline ll gcd(ll a,ll b) { if (!b) return a; return gcd(b,a%b); }
inline int ws(ll a) { int ret = 0; while (a) a /= 10,++ret; return ret; }
struct node
{
ll a,b,c;
inline node() { c = 1; }
inline void update()
{
ll g = gcd(b,c); b /= g,c /= g;
a += b/c; b %= c;
}
friend inline node operator + (const node &x,node &y)
{
node ret; y.update();
ret.a = x.a+y.a; ret.c = x.c*y.c/gcd(x.c,y.c);
ret.b = x.b*(ret.c/x.c)+y.b*(ret.c/y.c);
ret.update(); return ret;
}
friend inline node operator *(const node &x,const int &y)
{
node ret; ret.a = x.a*y;
ll g = gcd(x.c,y); ret.b = (y/g)*x.b; ret.c = x.c/g;
ret.update(); return ret;
}
inline void print()
{
if (!b) printf("%lld\n",a);
else
{
int t = ws(a);
for (int i = t+1;i--;) putchar(' ');
printf("%lld\n",b);
printf("%lld ",a);
for (int i = ws(c);i--;) putchar('-');
puts("");
for (int i = t+1;i--;) putchar(' ');
printf("%lld\n",c);
}
}
}ans;
int main()
{
freopen("10288.in","r",stdin);
freopen("10288.out","w",stdout);
while (scanf("%d\n",&N) != EOF)
{
ans.a = ans.b = 0; ans.c = 1;
for (int i = 1;i <= N;++i)
{
node tmp; tmp.a = 0,tmp.b = 1,tmp.c = i;
ans = ans + tmp;
}
ans = ans * N; ans.print();
}
fclose(stdin); fclose(stdout);
return 0;
}