您的位置:首页 > 其它

解题报告:Lightoj Harmonic Number 打表

2016-07-20 09:33 417 查看
Harmonic Number
Time Limit:3000MS    
Memory Limit:32768KB     64bit IO Format:%lld & %llu

Submit
Status

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

题意:

给定n,询问从1到n的倒数和。

思路:

T有1W,如果对于每个N(1e8)直接爆力肯定超时,如果考虑打表,题目给的内存是32M,全部打下来肯定会MLE,于是每隔100个数记录一个到表中,如果查询时从刚好小一点的数开始,每次查询复杂度o(1e2),整体复杂度o(1e8)+T*o(1e2),虽然前面的预处理复杂度高达o(1e8),但是每次只是进行一次除法和加法,还是能够接受的

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

double ans[1000001];

inline double work(int n){
int i = n/100;
double res = ans[i];
for(i=i*100+1;i<=n;i++){
res += 1.0/i;
}return res ;
}

int main()
{
int n=100000000;
ans[0]=0;double tmp=0;
for(int i=1;i<=n;i++){
tmp += 1.0/i;
if(i%100==0){
ans[(int)(i/100)]=tmp;
}
}

int T,t=0;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
printf("Case %d: %.9f\n",++t,work(n));
}return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: