题目:Light oj 1245 - Harmonic Number (II)
思路:枚举sqrt(n)以内的数字即可:
比如 n =38 枚举 tmp = sqrt(n) = 6
tmp n / tmp from to value num
1 38 20 38 1 19
2 19 13 19 2 7
3 12 10 12 3 3
4 9 8 9 4 2
5 7 6 7 5 2 ( 这里多算了一个6 )
6 6 = = 这里操作减去一个6 (判断 n/sqrt(n)==(int)sqrt(n) )
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
using namespace std;
long long solve(int n)
{
long long ans=0;
for(int i=1;i<=(int)sqrt(n);i++)
{
ans+=n/i;
if(n/i>n/(i+1))
ans+=(n/i-n/(i+1))*i;
}
if(n/((int)sqrt(n))==(int)sqrt(n))
ans-=(int)sqrt(n);
return ans;
}
int main()
{
int t;
scanf("%d",&t);
for(int cases=1;cases<=t;cases++)
{
int n;
scanf("%d",&n);
printf("Case %d: %lld\n",cases,solve(n));
}
return 0;
}