Time Limit: 1 Sec Memory Limit: 64 MB
Description
In mathematics, we suppose that f(1)=1, f(i)-f(i-1)=1/i, (2<=i<=n)
Input
Input starts with an integer T (≤ 10000), denoting the number of test cases.
Each case starts with a line containing an integer n (2 ≤ n ≤10^7).
Output
For each case, print the case number and the value of f(n). The answer should be rounded to 10 decimal places.
Sample Input
3
2
3
4
Sample Output
Case 1: 1.5000000000
Case 2: 1.8333333333
Case 3: 2.0833333333
思路:
f(i) - f(i - 1) = 1 / i =》 f(i) = 1 / 1 + 1 / 2 + 1 / 3 +…+1 / i ;
float精度不够,double打个表就行,但是内存只有64MB < 1e7 * 8,采取分段打表。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e7 + 5;
double a[maxn / 50 + 5];
void init() {
double ans = 1.0;
for(int i = 2; i <= maxn; i++) {
ans += 1.0 / double(i);
if(i % 50 == 0)
a[i / 50] = ans;
}
}
int main() {
int t, p = 1, n;
init();
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
double ans = a[n / 50];
for(int i = n / 50 * 50 + 1; i <= n; i++)
ans += 1.0 / double(i);
printf("Case %d: %.10lf\n", p++, ans);
}
return 0;
}