【题解】LightOJ1245 Harmonic Number (II) 数学知识

题目链接
这里写图片描述

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


找规律题。对于i∈[1,sqrt(n)],直接算;对于其他情况,对于一个数x,我们假设n/x的值为i,显然i∈[1,sqrt(n)],通过举例或者打表可以发现,这样的i的个数为n/i-n/(i+1),所以可以枚举i,答案累加i*(n/i-n/(i+1)),注意判断有没有多加。

#include<cstdio>
#include<cmath>
typedef long long ll;
int main()
{
    //freopen("in.txt","r",stdin);
    int t,ca=0;
    ll n,ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld",&n);ans=0;
        for(int i=1;i<=sqrt(n);i++)
        {
            ans+=n/i+i*(n/i-n/(i+1));
            if(n/i==i)ans-=i;
        }
        printf("Case %d: %lld\n",++ca,ans);
    }
    return 0;
}

总结

找规律

猜你喜欢

转载自blog.csdn.net/qq_41958841/article/details/82729597