【数论】UVa 11526 - H(n)

时间:2022-05-18 06:27:18

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

 long long H(int n)

 {
  long long res = ;
  for( int i = ; i <= n; i=i+ )   {
    res = (res + n/i);
  }
  return res;
}

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));

代码:

 #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long LL;
LL H(LL n)
{
LL res = ;
LL pre = n, next_pos = n, tmp;
for(LL i = ; i <= n; i++)
{
res += n/i;
tmp = n/i;
if(tmp != pre)
{
next_pos = n/tmp;
res += (next_pos-i)*tmp;
pre = tmp;
i = next_pos;
}
}
return res;
}
int main()
{
int T; scanf("%d", &T);
while(T--)
{
LL n; scanf("%lld", &n);
printf("%lld\n", H(n));
}
return ;
}