【题目链接】: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;
}
原文地址:http://blog.csdn.net/u013050857/article/details/46007937