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.
#include <cstdio>
#include<iostream>
#include <cmath>
using namespace std;
long long n,m,res;
int main(){
int t,kase=1,r,l;
scanf("%d",&t);
while(t--){
cin>>n;
res=0;
m=int(sqrt(n));
for(int i=1;i<=m;i++){
if(n/i!=i)
res+=n/i;
l=n/i;
r=n/(i+1);
res+=i*(l-r);
}
printf("Case %d: %lld\n",kase++,res);
}
return 0;
}
本文介绍了一种解决1234-HarmonicNumber问题的方法,通过优化整数除法来提高计算效率。输入包含多个测试用例,每个用例给出一个整数n,需要计算H(n)的值。
431

被折叠的 条评论
为什么被折叠?



