I was trying to solve problem ‘1234 - Harmonic Number’, I wrote the following code
long long H( int n ) {
long long res = 0;
for( int i = 1; i <= n; i++ )
res = res + n / i;
return res;
}
Yes, my error was that I was using the integer divisions only. However, you are given n, you have to find H(n) as in my code.
Input
Input starts with an integer T (≤ 1000), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n < 231).
Output
For each case, print the case number and H(n) calculated by the code.
Sample Input
11
1
2
3
4
5
6
7
8
9
10
2147483647
Sample Output
Case 1: 1
Case 2: 3
Case 3: 5
Case 4: 8
Case 5: 10
Case 6: 14
Case 7: 16
Case 8: 20
Case 9: 23
Case 10: 27
Case 11: 46475828386
分析: 题意很明显,但是时间也是很明显不够的,这里就用到了 常用的减少时间复杂度的思想,从结果出发,看什么样 的情况会导致这样结果 。
我们从结果出发 n/i 肯定有一些区间的值会导致同一个结果,我们只要找到什么样的区间会导致同一个结果就好了,同时我们还要知道如何才可以枚举 所有的可能结果。
看代码
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define ULL unsigned long longconst int N = 1e6+11;
const int M = 1e6+11;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
const int LL inff = 0x3f3f3f3f3f3f3f3f;LL get(LL n,LL x){ // 结果是x的时候,什么样的值才会导致这个结果LL a=n/x;LL b=n/(x+1)+1; // 区间 [b,a] 找规律return (a-b+1)*x;
}int main(){int T ;scanf("%d",&T);int cas=1;while(T--){LL n;scanf("%lld",&n);LL ans=0;for(LL i=1;i*i<=n;i++){ // 枚举 所有的n/i 的结果 LL a=i; LL b=n/i;ans+=get(n,a);if(a!=b) ans+=get(n,b);}printf("Case %d: %lld\n",cas++,ans);}
return 0;
}