LightOJ-1245-Harmonic Number (II)基础数论

1245 - Harmonic Number (II)
Time Limit: 3 second(s)Memory Limit: 32 MB

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

Output for Sample Input

11

1

2

3

4

5

6

7

8

9

10

2147483647

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

 


题意

求f(n)=n/1+n/2.....n/n,其中n/i保留整数;


题解1


建议读者手动把 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<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;
}

题解2

另外一个一个思路就是通过图像来判断.首先我们来画出y = n / x 的图像.



看下这个图 m = sqrt(n), 我们可以看到这个题目的答案就是y = n/x的这个图像,和x=n,y=n,x=0,y=0;曲线的封闭图像中的整数点的个数.

中间红色的区域就是 sum i从1和n累加 n/i. 而整个区域的整数个数就是 2*ans - m*m ,因为m*m是重复加的.


代码 

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
    int caset,cas=0;scanf("%d",&caset);
    while(caset--) {
        ll n;scanf("%lld",&n);
        ll ans = 0,m=sqrt(n);
        for(ll i=1;i<=m;i++) ans += n/i;
        ans<<=1;
        ans-=m*m;
        printf("Case %d: %lld\n",++cas,ans);
    }
    return 0;
}


  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值