Harmonic Number (II)
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/1+n/2+…+n/n的值
思路: 题所给数据范围太大,故用题中所给方法暴力肯定是不行的,所以要找规律,我看其他大佬的博客学会了两种
1.大佬博客
y=n/x,是一个反比例函数,关于y=x对称,所以我们求n/x的和,相当于求图形的面积,可以分成两份一样的面积(在y=x处分,即一份x从1到sqrt(n),一份从sqrt(n)到n),此时x=sqrt(n),但两份面积有重叠,所以要减去重叠部分面积sqrt(n)*sqrt(n)(可能光看这些文字想不明白,所以可去看上述博客里的图片,一目了然)
2.大佬博客
这第二种方法就是找sqrt(n)到n之间n/x的和,前半段可暴力,不会超时,后半段按规律相加即可,上述博客叙述的很详细,我就不再多赘述了
AC代码:
第一种:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
int kk=1;
while(t--)
{
int x;
scanf("%d",&x);
long long sum=0;
int m=sqrt(x);
for(int i=1; i<=m; i++)//前半段面积
sum+=x/i;
sum=sum*2-m*m;//*2-重叠面积
printf("Case %d: %lld\n",kk++,sum);
}
第二种:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
int t,n,i,j=1,k;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
k=sqrt(n);
long long sum=0;
for(i=1;i<=k;i++)//前半段和
sum+=n/i;
for(i=1;i<=k;i++)//后半段和
sum+=(n/i-n/(i+1))*i;
if(n/k==k)//减算重的
sum-=k;
printf("Case %d: %lld\n",j++,sum);
}
return 0;
}