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
题意:
谷物盒中的优惠券编号为1到N,每一个都需要一套奖品(谷物)。盒子,当然。每个盒子有一张优惠券,平均需要多少个盒子才能完成。
思路:
假设当前有k种谷物,那么获取新的谷物的概率,所以需要步数的期望是
.求和得到步数的期望是
。需要注意的是n=1的时候需要特判一下,先把33以内的分母打表(方便运算)。
AC代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5 + 7;
ll gcd(ll a,ll b){return b ? gcd(b,a % b) : a;}
ll lcm(ll a,ll b){return a / gcd(a,b) * b;}
ll get_lenth(ll n)
{
ll pos = 0;
if(n == 0) return 1;
while(n){
n /= 10;
pos++;
}
return pos;
}
ll fm_map[34];
void get_map()
{
fm_map[1] = 1;
for(int i = 2;i < 34;++i) fm_map[i] = lcm(fm_map[i - 1],i);
}
int main()
{
ios::sync_with_stdio(0);
ll n;
get_map();
while(cin >> n){
ll cnt = 0,pos,tmp = n,fm = fm_map[n],fs = fm;
for(int i = n - 1;i > 0;--i){
tmp = fm / i * n + fs;
cnt += tmp / fm;
fs = tmp % fm;
}
pos = gcd(fs,fm);
fs /= pos;fm /= pos;
if(fs && cnt){
ll len = get_lenth(cnt);
for(int i = 0;i <= len;++i) cout << ' ';
cout << fs << endl;
len = get_lenth(fm);
cout << cnt << ' ';
for(int i = 0;i < len;++i) cout << '-';
cout << endl;
len = get_lenth(cnt);
for(int i = 0;i <= len;++i) cout << ' ';
cout << fm << endl;
}
else cout << (cnt ? cnt : cnt + 1) << endl;
}
return 0;
}