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
题解:
建议读者手动把 24 所有的数 用24除完以后得到的数写出来会发现一个规律:
我们还是枚举 1~sqrt(n);
对于1 和 2:n/1 = 24, n/2 = 12 ——> 13 到 24 的除后的结果都是 1
对于2 和 3: n/2 = 12, n/3 = 8 ——> 9 到 12 的除后的结果都是 2
对于3 和 4: n/3 = 8, n/4 = 6 ——> 7 到 8 的除后的结果都是 3
对于4 和 5: n/4 = 6, n/5 = 4 ——> 5 到 6 的除后的结果都是 4
而我们已经得到了 n/1,n/2,n/3,n/4的值.n/(5-6)的值是4,n/(7-8)的值是3,n/(9-12)的值是2,n/(13-24)的值是1
综上我们似乎找到了规律.
但是还有一个问题,sprt(n)这里存在边界问题,会加多了, 可以根据题目的样例自己推一下
代码:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t ;
scanf("%d",&t);
for(int cas=1;cas<=t;cas++)
{
int n,m;
scanf("%d",&n);
m=sqrt(n*1.0);
long long ans=0;
for(int i=1;i<=m;i++)
{
ans+=n/i;
if((n/i)>(n/(i+1)))
{
ans+=((n/i)-(n/(i+1)))*i;
}
}
if(m==n/m)
{
ans=ans-m;
}
printf("Case %d: %lld\n",cas,ans);
}
return 0;
}