一、题目描述
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
二、算法分析说明与代码编写指导
法一:直接套除法分块模板
法二:找规律
他的说法我没太看懂(https://blog.youkuaiyun.com/m0_38013346/article/details/79829509?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task)
法三:数形结合(https://blog.nowcoder.net/n/73b00ed011354eeaaaca1235bb15f7f7)
绘制曲线 y = n / x。即使因为整除而截断了小数部分,图形依然是关于 y = x 对称的。
具体解法可在原文看图。
三、AC 代码
法一(1996 ms):
#include<cstdio>
#include<cmath>
#pragma warning(disable:4996)
unsigned t; unsigned long long n, h, q, L, R;
int main() {
scanf("%u", &t);
for (unsigned i = 1; i <= t; ++i) {
scanf("%llu", &n); h = 0;
for (L = 1; L <= n; L = R + 1) {
q = n / L; R = n / q; h += q * (R - L + 1);
}
printf("Case %u: %llu\n", i, h);
}
return 0;
}
法二(777 ms):
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e6+10;
int main()
{
int caset,cas = 0;scanf("%d",&caset);
while(caset--)
{
ll n,i;
scanf("%lld",&n);
ll m = sqrt(n);
ll ans = 0;
for(i=1;i<=m;i++) {
ans += (n/i);
ans += i*(n/i - n/(i+1));
}
i--;
if(n/i == m) ans -= m;
printf("Case %d: %lld\n",++cas,ans);
}
return 0;
}
法三(408 ms):
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
ll T,N;
ll solve(ll x){
ll len = sqrt(x),res = 0;
for(int i = 1;i<=len;i++){
res += x/i;
}
return res*2-len*len;
}
int main(){
cin>>T;
int kase = 0;
while(T--){
scanf("%lld",&N);
printf("Case %d: %lld\n",++kase,solve(N));
}
return 0;
}
417

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



