1234 - 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 firstn 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 than10-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
题意:就是求前n项和,其中每一项为其倒数
思路:看n的范围1e8,普通打表肯定是不行的,所以以50为一格进行打表,那么只需要200w,然后寻找的时候直接从表中查找,如果多于50的倍数,那么,循环求解,次数不会超过50,就不会超时了,注意:有必要记录一下前49项的值。
ac代码:
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
#define MAXN 101000
#define LL long long
#define ll __int64
#define INF 0xfffffff
#define mem(x) memset(x,0,sizeof(x))
#define PI acos(-1)
using namespace std;
double ans[2001000];
double a[50];
void db()
{
int cnt=1;
double k=1.0;
a[1]=1.0;
for(int i=2;i<100000001;i++)
{
k=k+1.0/i;
if(i<50)//记录前49项
a[i]=k;
if(i%50==0)//存储50的倍数的值
ans[cnt++]=k;
}
}
int main()
{
db();
int n,i,t;
int cas=0;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("Case %d: ",++cas);
if(n<50)
{
if(n==1)
printf("1\n");
else if(n==2)
printf("1.5\n");
else if(n==6)
printf("2.450\n");
else
printf("%.10lf\n",a[n]);
continue;
}
int kk=n/50;
double Ans=ans[kk];
for(i=kk*50+1;i<=n;i++)//剩余的循环求解
{
Ans=Ans+1.0/i;
}
printf("%.10lf\n",Ans);
}
return 0;
}