码迷,mamicode.com
首页 > 其他好文 > 详细

UVA - 11526 H(n) (数学)

时间:2015-05-26 16:11:48      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:acm   数学   uva   

题目链接】:click here~~

题目大意

What is the value this simple C++ function will 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 first line of input is an integer T (T ≤ 1000) that indicates the number of test cases. Each of thenext 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

就是求n/1...n/n的值

解题思路】我们改变一下循环里面的长度,很容易想到只要循环到sqrt(n),最后结果乘以2再减去sqrt(n)平方回来的结果就是答案了。

代码:

//uva 11526
#include <bits/stdc++.h>
using namespace std;
long long t,n;
long long solve(int n)//超时
{
    long long res=0;
    for(int i=2; i<n; i++)
    {
        res+=n/i;
    }
    return res;
}
long long W(long long n)
{
    int t=sqrt(n+0.5);
    long long  res = 0;
    for(int i=1;i<=t;i++) res+=n/i;
    return (res<<1)-t*t;
}
long long  H(long long  n)//或者合并结果相同的项,答案是一样的
{
    long long  res = 0;
    long long  L=1,R=0;
    while(L<=n)
    {
        long long  p=n/L;
        R=n/p;
        res+=p*(R-L+1);
        L=R+1;
    }
    return res;
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld",&n);
        //printf("%lld\n",solve(n)+n+1);
       // printf("%lld\n",H(n));
        printf("%lld\n",W(n));
    }
    return 0;
}



UVA - 11526 H(n) (数学)

标签:acm   数学   uva   

原文地址:http://blog.csdn.net/u013050857/article/details/46007937

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!