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 ", cnt ++, sum); 44 } 45 return 0; 46 47 //2 147 483 648 48 }