【数论】UVa 11526 - H(n)

Posted on 2015-03-10 19:32  LLGemini  阅读(170)  评论(0编辑  收藏  举报

What is the value this simple C++ function will return?

 1 long long H(int n)
 2 
 3 {
 4   long long res = 0;
 5   for( int i = 1; i <= n; i=i+1 )
 6 
 7   {
 8     res = (res + n/i);
 9   }
10   return res;
11 }

 

Input
  The first line of input is an integer T (T ≤ 1000) that indicates the number of test cases. Each of the next T line will contain a single signed 32 bit integer n.

Output
  For each test case, output will be a single line containing H(n).

Sample Input
2
5
10

Sample Output
10
27

题意:求上述函数的返回值;

分析:简单讲就是求出一个tmp=[n/i]后计算一下这个数会出现多少次,方法就是n/tmp,求得的数是满足n/i==tmp的最大i值,然后继续更新i值即可。算法复杂度会由O(n)降为O(sqrt(n));

代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<cmath>
 6 #include<algorithm>
 7 using namespace std;
 8 typedef long long LL;
 9 LL H(LL n)
10 {
11     LL res = 0;
12     LL pre = n, next_pos = n, tmp;
13     for(LL i = 1; i <= n; i++)
14     {
15         res += n/i;
16         tmp = n/i;
17         if(tmp != pre)
18         {
19             next_pos = n/tmp;
20             res += (next_pos-i)*tmp;
21             pre = tmp;
22             i = next_pos;
23         }
24     }
25     return res;
26 }
27 int main()
28 {
29     int T; scanf("%d", &T);
30     while(T--)
31     {
32         LL n; scanf("%lld", &n);
33         printf("%lld\n", H(n));
34     }
35     return 0;
36 }
View Code