题意:让我们求f(n)=n/1+n/2+n/3+......+n/n;同时注意n/i取整;
思路:首先我们先看数据的范围,n (1 ≤ n < 2 31),数据范围太大,如果我们按 照题目中的代码直接暴力肯定超时,那么,我们就要优化代码;
f=n/x这个函数关于y = x 对称对称点刚好是sqrt(n),于是就简单了直接 求sum+n/i (i*i<n && i >=1),然后乘以2,再减去i*i即可。
例如:当n==10时,m=sqrt(10)==13,f(10)==(10+5+3)*2-3*3=27;
关于m对称,左右相差m*m,左边10+5+3=18,右边2+2+1+1+1+1+1=9,和左边相差3*3=9,
故,这道题我们就可以简化了;
公式:1.m=sqrt(n);
2. f(n)=(n/1+n/2+n/3+......+n/k)*2-m*m;(n/k<=m);
题目:
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
|。 /| 。 /| 。 /| 。 /| 。 /| * 。 /
sqrt(n)|———————————/。| * / | 。| * / *| 。| / | 。| / * |* 。
_______|_/_________|______________。___sqrt(n)
由图可知,可将题转化为求每个整数坐标点对应的矩形面积,由图形对称可知,求到sqrt(n),*2即可,
因多加了一次边长为sqrt(n)正方形的面积,故减去即可
代码:
#include<stdio.h>
#include<math.h>
int main()
{int t,k=1;scanf("%d",&t);while(t--){long long n,sum=0;scanf("%lld",&n);int m=(int)sqrt(n);for(int i=1; i<=m; i++)sum=sum+n/i;sum*=2;sum-=m*m;printf("Case %d: %lld\n",k++,sum);}return 0;
}