Time Limit: 3 second(s) | Memory Limit: 32 MB |
In mathematics, the nth harmonic number isthe 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 nthharmonic number. Errors less than 10-8 will be ignored.
Sample Input | Output for Sample Input |
12 1 2 3 4 5 6 7 8 9 90000000 99999999 100000000 | 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+1/2+1/3+……+1/n ;
思路:分段打表,将每1000的和存一下,需要计算时找出对应的1000的权值,再计算后面的部分相加即可
下面附上我的代码:
#include <cstdio>
#include <cmath>
double a[100005];
void init(){
int tm = 1;
a[0] = 0;
for (int i = 1; i <= 100002; ++i){
a[i] = a[i-1];//a[i]计算的从(i-1)*1000+1到i*1000的和
for (int j = tm; j <= tm+999; ++j){
a[i] += 1.0/j;
}
tm = tm+1000;
}
}
int main(){
int t;
scanf("%d",&t);
init();
int Case = 1;
while (t--){
int n;
scanf("%d",&n);
int r = n/1000*1000;//找出他的对应1000的位置
for (int i = r+1; i <= n; ++i){//计算一下剩余的值的和
tmp += 1.0/i;
}
double tt;
tt = a[n/1000];
//printf("%lf %lf\n",tt,tmp);
double ans = tt+tmp;
printf("Case %d: %.9lf\n",Case++,ans);
}
return 0;
}