【題解】LightOJ1245 Harmonic Number (II) 數學知識
阿新 • • 發佈:2018-12-10
Input
Input starts with an integer T (≤ 1000), denoting the number of test cases.
Each case starts with a line containing an integer n (1 ≤ n < 231).
Output
For each case, print the case number and H(n) calculated by the code.
Sample Input
11
1
2
3
4
5
6
7
8
9
10
2147483647
Sample Output
Case 1: 1
Case 2: 3
Case 3: 5
Case 4: 8
Case 5: 10
Case 6: 14
Case 7: 16
Case 8: 20
Case 9: 23
Case 10: 27
Case 11: 46475828386
找規律題。對於i∈[1,sqrt(n)],直接算;對於其他情況,對於一個數x,我們假設n/x的值為i,顯然i∈[1,sqrt(n)],通過舉例或者打表可以發現,這樣的i的個數為n/i-n/(i+1),所以可以列舉i,答案累加i*(n/i-n/(i+1)),注意判斷有沒有多加。
#include<cstdio>
#include<cmath>
typedef long long ll;
int main()
{
//freopen("in.txt","r",stdin);
int t,ca=0;
ll n,ans;
scanf("%d",&t);
while(t--)
{
scanf("%lld",&n);ans=0;
for(int i=1;i<=sqrt(n);i++)
{
ans+=n/i+i*(n/i-n/(i+1));
if(n/i==i)ans-=i;
}
printf ("Case %d: %lld\n",++ca,ans);
}
return 0;
}
總結
找規律