11526-h (N)
Time limit:5.000 seconds
Http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem &problem=2521
What is the value of this simple C + + function would return?
Long long H (int n) {
Long long res = 0;
for (int i = 1; I <= n; i=i+1) {
Res = (res + n/i);
}
return res;
}
Input
The the "a" of input is a integer t (T <= 1000) that indicates the number of test cases. Each of the next T-line would contain a single signed bit integer n.
Output
For the each test case, output would be a single line containing H (n).
Sample input Output for sample input
How do I calculate sum{[n/i]}? (1<=i<=n) (n<=2147483647)
n too big, hard to calculate certainly not, we first observe an example, see whether can draw some conclusions.
When n=20, the and type expands to
20+10+6+5+4+3+2+2+2+2+1+1+1+1+1+1+1+1+1+1
Note that the same number of the following is too many, may wish to simplify the following:
20+10+6+5+1* (20-10) +2* (10-6) +3* (6-5) +4* (5-4)
= (20+10+6+5) + (20+10+6+5) -4*4
=2 (20+10+6+5) -4*4
Maybe, we can
This article URL address: http://www.bianceng.cn/Programming/sjjg/201410/45351.htm
Thus, the complexity is reduced from O (n) to O (√n).
Complete code:
/*0.206s*/
#include <cstdio>
#include <cmath>
typedef long Long ll;
inline ll ans (ll N)
{
ll r = 0, m = sqrt (n), I;
for (i = 1; I <= m; ++i) R + = n/i;
Return (r << 1)-M * m;
}
int main ()
{
int t;
ll N;
scanf ("%d", &t);
while (t--)
{
scanf ("%lld", &n);
printf ("%lld\n", ans (n));
}
return 0;
}