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 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.
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.
每张彩票有一张图案,每次买一张彩票,图案有 n 种,只有集齐这 n 种图片才能兑奖,平均情况下需要买多少次彩票才能兑奖。
分析: 每张彩票出现的概率都是 1/n 假设此时手中有 k 种图片,那买 t 次可以得到一张新的图片的概率是: p(t) = (k/n)^(t-1) * (1-k/n) 令(k/n) = s 那在手中有 k 种图片的前提下,拿到的下一张图片是新的图片的期望次数是: 1*P(1) + 2*P(2) + 3*P(3) + … + n*P(n) + … = (1-s)*( 1 + 2*s + 3*s^2 + 4*s^3 + …) = 1 + 2*s + 3*s^2 + 4*s^3 + … - s - 2*s^2 - 3*s^3 -… = 1 + s + s^2 + s^3 + … [泰勒级数求和公式] = 1/(1-s) = n/(n-k)
所以:平均情况下需要买的次数是
ans = n * ( 1 + 1/2 + 1/3 + … + 1/(n-1) + 1/n );
注意
// 判断分母的位数 LL tmp = ansfm; int cont = 0; while(tmp / 10) { cont ++; tmp = tmp / 10; }可以直接改成 …(´・ω・`)
int cont = log10(ansfm);