Harmonic Number Time Limit:3000MS Memory Limit:32768KB 64bit IO Format:%lld & %llu
Description
In mathematics, the nth harmonic number is the sum of the reciprocals of the first n natural numbers:
In this problem, you are given n, you have to find Hn.
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n ≤ 108).
Output
For each case, print the case number and the nth harmonic number. Errors less than 10-8 will be ignored.
Sample Input
12
1
2
3
4
5
6
7
8
9
90000000
99999999
100000000
Sample Output
Case 1: 1
Case 2: 1.5
Case 3: 1.8333333333
Case 4: 2.0833333333
Case 5: 2.2833333333
Case 6: 2.450
Case 7: 2.5928571429
Case 8: 2.7178571429
Case 9: 2.8289682540
Case 10: 18.8925358988
Case 11: 18.9978964039
Case 12: 18.9978964139
这题是单调级数部分求和,网上有公式,不过不知道公式也是没关系的,毕竟这个知识点也偏门了点。。。
我用的方法是打表记录1/i (1<=i<=n),根据题意,n最大为一亿,将一亿个结果记录下来肯定是不可行的,但是可以记录百万级个结果。下面的代码中,我开了一个250万的数组,0到一亿范围内,每40个数记录一个结果,即是分别记录1/40,1/80,1/120,...,1/一亿,这样对于输入的每个n,最多只需执行39次求倒数运算,大大节省了时间。
注意的是,a[0] = 0,只是为了使得当n==1时不用单独判断。
AC Code:
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cstring> 5 #include <cmath> 6 7 using namespace std; 8 9 const int maxn = 2500001; 10 double a[maxn] = {0.0, 1.0}; 11 12 int main() 13 { 14 int t, n, ca = 1; 15 double s = 1.0; 16 for(int i = 2; i < 100000001; i++) 17 { 18 s += (1.0 / i); 19 if(i % 40 == 0) a[i/40] = s; 20 } 21 scanf("%d", &t); 22 while(t--) 23 { 24 scanf("%d", &n); 25 int x = n / 40; 26 // int y = n % 40; 27 s = a[x]; 28 for(int i = 40 * x + 1; i <= n; i++) s += (1.0 / i); 29 printf("Case %d: %.10lf\n", ca++, s); 30 } 31 return 0; 32 }