您的位置:首页 > 其它

LightOJ 1245 Harmonic Number (II)

2015-10-09 14:45 561 查看
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=70017#problem/G

Harmonic Number (II)

Description

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,让你求Σn/i,i从1->n.

解析:例如10

   那么10/1=10;

     10/2=5;

   则n/i为1的数和为 1*(10-5);  

   同时对应着n/1的数为36,是以两段对应和为5+1*(10-5);

   同理,10/3=3, 和为 5+2*(5-3)

    ...

   当n/i和i产生重合或者交叉时,就可以退出策画了

   全部策画流程如下

   i      1   2   3   4   5   6   7   8   9   10

   n/i  10  5   3   2   2   1   1   1   1    1

       如上所示,在策画i=1时,ans+=10, ans+=10-5
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <limits>
#include <queue>
#include <stack>
#include <vector>
#include <map>

using namespace std;

#define N 10005000
#define INF 0x3f3f3f3f
#define PI acos (-1.0)
#define EPS 1e-8
#define P (1000000000+7)
#define met(a, b) memset (a, b, sizeof (a))

typedef long long LL;

int main ()
{
int t, n, nCase = 1;
scanf ("%d", &t);

while (t--)
{
scanf ("%d", &n);
LL ans = 0, i;
for (i=1; i<=sqrt (n); i++)
{
ans += n / i;
if (n / i > n / (i+1))
ans += (n / i - n / (i+1)) * i;
}

if (n / (i - 1) == i - 1)//判断重合的时候要减去重复的
ans -= n / (i - 1);
printf ("Case %d: %lld\n", nCase++, ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: