原题:
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个图案,平均需要买多少张彩票才能中奖?
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a,long long b)
{
if(a%b==0)
return b;
return gcd(b,a%b);
}
int main()
{
ios::sync_with_stdio(false);
long long n;
while(cin>>n)
{
long long fra=1,num=1;
for(long long i=n-1;i>=1;i--)
{
fra=fra*i+num*n;
num=num*i;
long long tmp=gcd(fra,num);
fra/=tmp;
num/=tmp;
}
long long a=fra/num,b=fra-(fra/num)*num,c=num;
if(c==1)
cout<<a<<endl;
else
{
string s=to_string(num);
for(int i=0;i<=to_string(a).size();i++)
cout<<" ";
cout<<b<<endl;
cout<<a<<" ";
for(int i=0;i<s.size();i++)
cout<<'-';
cout<<endl;
for(int i=0;i<=to_string(a).size();i++)
cout<<" ";
cout<<num<<endl;
}
}
return 0;
}
解答:
紫书上的例题,自己做的时候直接用高中的方法去解期望。结果发现自己想错了,应该按照递推的方法去考虑。
现在假如手里已经有了k个图案,那么下次再买彩票是自己没有的图案的概率是1-(k/n),设s=k/n,那么按照期望的思想,拿一新的需要t的概率
st−1(1−s)
,平均拿取的次数就是
(1−s)(1+2s+3s2+...
,按照高中数列的知识算出公式,然后取极限得到公式为n/(n-k),然后对k等于1到n累加求和即可。
最后答案要模拟分数运算,记得用公约数约分。