• 【数论】UVa 11526


    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
    ", H(n));
    34     }
    35     return 0;
    36 }
    View Code
  • 相关阅读:
    ExpandableListView实现子Item的点击事件
    使用AndroidStudio自动生成JavaDoc文档
    将Asset中的数据库文件拷贝出来使用
    拦截webview调用系统浏览器打开链接
    配置国内 Docker Registry Mirror
    解决mysql 主从数据库同步不一致的方法
    讯时网关路由规则小结
    Docker 导出 & 导入
    Centos 7 安装Docker-ce记录
    Go Rand小结
  • 原文地址:https://www.cnblogs.com/LLGemini/p/4327016.html
Copyright © 2020-2023  润新知