Harmonic Number (II) 數學找規律

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

 

 

思路: 找規律這件事,emmm.....

   注意sqrt(n)這個數,數之間的差與後面數的個數。。。。。

   寫幾個完整的例子,努力尋找規律! 

 

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <math.h>
 5 #include <algorithm>
 6 #include <queue>
 7 #include <map>
 8 #include <stack>
 9 #include <deque>
10 #include <iostream>
11 using namespace std;
12 typedef long long LL;
13 const LL N = 10000010;
14 
15 map<int, bool> check; 
16 int prime[7000000];
17 
18 long long H( int n ) {
19     long long res = 0;
20     for( int i = 1; i <= n; i++ )
21         res = res + n / i;
22     return res;
23 }
24 
25 int main()
26 {
27     LL i, p, j, n, t, cnt = 1;
28     LL sum;
29 
30     scanf("%lld", &t);
31     while(t--) {
32         sum = 0;
33         scanf("%lld", &n);
34         for(i = 1; i <= (LL)sqrt(n); i++) {
35         //    cout << "i: " << i << endl;
36             sum += (n / i - n / (i + 1)) * i;
37             sum += n / i;
38         }
39         if(n / (LL)sqrt(n) == (LL)sqrt(n)) {
40             // sum -= (n / (LL)(sqrt(n)) - n / (LL)(sqrt(n) + 1)) * (i - 1);
41             sum -= (LL)sqrt(n);
42         }
43         printf("Case %lld: %lld\n", cnt ++, sum);
44     }
45     return 0;
46 
47     //2 147 483 648
48 }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章