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 < 2的31次方).
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,求出f(n)=n/1+n/2+n/3+n/4+...+n/n;
题解:先求出前sqrt(n)项的和,再求后面的。具体操作根据例题来了解。
例如:
10 10/2 10/3 10/4 ... 10/10;
先求出前 sqrt(n)项和
第二项与第一项的差是后面所有等于一的个数
第三项与第二项的差是后面所有近似于等于二的个数
当n/i==i时,n/i 计算了两边,所以需要减去 i
方法2:利用对称性。
对于函数y=1/x,它关于y=x对称。
所以求f(n)的时候,可以先求前sqrt(n)项的和,然后乘以2。
注意:在sqrt(n)这个点,前面已经计算过了,结果乘以2的时候又计算了一次。
所以求最后结果的时候需要减去一次。
其实两种方法是一样的,只是后一种比较好理解。*-**-*
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
long long H(int n)
{
int i;
long long res=0;
for(i=1; i<=(int)sqrt(n); i++)
{
res+=n/i;
if(n/i>n/(i+1))
res+=(long long)((n/i-n/(i+1))*i);
}
i--;
if(n/i==i)
res-=i;
return res;
}
int main()
{
int t;
scanf("%d",&t);
int o=1;
while(t--)
{
long long n;
scanf("%lld",&n);
H(n);
printf("Case %d: ",o++);
printf("%lld\n",H(n));
}
return 0;
}
方法2:代码。
#include<stdio.h>
#include<math.h>
int main()
{
int t,o=1;
scanf("%d",&t);
while(t--)
{
long long n;
scanf("%lld",&n);
long long t,sum=0;
t=(long long)sqrt(n);
for(int i=1;i<=t;i++)
sum+=(n/i);
sum*=2;
sum=sum-t*t;
printf("Case %d: %lld\n",o++,sum);
}
return 0;
}