【LightOJ - 1245】 Harmonic Number (II) 【数论 - 常见的减少时间复杂度的思想】

88 篇文章 0 订阅
48 篇文章 0 订阅

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 肯定有一些区间的值会导致同一个结果,我们只要找到什么样的区间会导致同一个结果就好了,同时我们还要知道如何才可以枚举 所有的可能结果。
看代码

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define ULL unsigned long long

const int N  = 1e6+11;
const int M  = 1e6+11;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
const int LL inff = 0x3f3f3f3f3f3f3f3f;

LL get(LL n,LL x){  //  结果是x的时候,什么样的值才会导致这个结果
    LL a=n/x;
    LL b=n/(x+1)+1;   // 区间 [b,a] 找规律
    return (a-b+1)*x;
}

int main(){
    int T ;scanf("%d",&T);
    int cas=1;
    while(T--){
        LL n;scanf("%lld",&n);
        LL ans=0;
        for(LL i=1;i*i<=n;i++){  //  枚举 所有的n/i 的结果 
            LL a=i; LL b=n/i;
            ans+=get(n,a);
            if(a!=b) ans+=get(n,b);
        }
         printf("Case %d: %lld\n",cas++,ans);
    }
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值