Uva11526
本题转载于传送门
题意:
题目要你求sum【n/i】(from 1 to n)(注意这里是int除法)
思路:
直接算,肯定超时n最大2^32。
所以要想办法优化:
n=20时,和式展开为
20+10+6+5+4+3+2+2+2+2+1+1+1+1+1+1+1+1+1+1
注意到后面相同的数太多,不妨化简下:
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)-4x4
所以复杂度降到了O(√n)了(也就是2^16~~1e7肯定不会超时了)
总结:
对于这道题,数学归纳法,以及找规律的能力还有所欠缺。
AC
#include <iostream>
#include <cmath>
using namespace std;
typedef long long ll;
int main()
{
int t;
cin>>t;
while(t--)
{
ll n;
cin>>n;
ll spow=sqrt(n);
ll ans=0;
for(int i=1; i<=spow; i++)
{
ans+=n/i;
}
ans*=2;
ans-=spow*spow;
cout<<ans<<endl;
}
return 0;
}