您的位置:首页 > 其它

Harmonic Number (II)(数论)

2020-05-11 04:11 225 查看

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,i从1到n;
解法一 根号n之前的累加 m=Σn/i;n<sqrt(n),m*2-sqrr(n)*sqrt(n);我还不知道怎么推出来的

在这里插入代码片
#include<stdio.h>
#include<math.h>

int main()
{
int t,kk=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",kk++,sum);
}
return 0;
}

解法二 估计也由一来的
因为从n/2 到 n 都是1 n/2 到 n/3 都是2 而 根号n之前的直接暴力累加
比如 13
根号13=3 ,13/1 + 13/2 +13/3 13/1-13/2(13,12,11,10,9,8,7) 13/2-13/3(6,5) 13/3-13/4 (4)
而 当根号n = n/根号n 时
比如 9 9/3=3 而 9/2-9/3 4 9/3-9/4(3),那么3 就算了两次 所以要减去。

在这里插入代码片
#include<math.h>
#include<stdio.h>
#include<string.h>
int n,i,j,k,l,flag=1,t;
int main()
{
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
long long k=sqrt(n);//求到2^16次方是不会超市的
long long m=0;
for(i=1;i<k+1;i++)
{
m+=n/i;//前边的按正常计算 ,可计算到前1/k。
if(n/i>n/(i+1))//算了k个数后,开始找规律。
m+=(n/i-n/(i+1))*i;//从n到n/2这些值都为1,从n/2到n/3之间的数都为2...;
}
if(k==n/k)
m=m-k;
printf("Case %d: %lld\n",flag++,m);
}
return 0;
}
Starry_Sky_Dream 原创文章 50获赞 4访问量 2351 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: