题意:
求1/1 + 1/2 + 1/3 + …… + 1/n 的和。n <= 1e8
分析:
打表记录。开1e8的数组会爆内存,学到 开个1e6的数组,每100个数记录一次,然后再遍历加剩下的。
代码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
double sum[1000005];
void dabiao()
{
sum[0] = 0;
sum[1] = 1.0;
int t = 1;
for(int i = 2; i <= 100000000; i++)
{
sum[t] += (double)1/i;
if(i%100 == 0) {t++; sum[t] = sum[t-1];}
}
}
int main()
{
int n, t, kase = 1; cin >> t;
dabiao();
while(t--)
{
cin >> n;
int a = n/100;
double ans = sum[a];
int m = a*100;
for(int i = m+1; i <= n; i++)
{
ans += (double)1/i;
}
cout << "Case "<< kase++ << ": ";
printf("%.10f\n", ans);
}
return 0;
}