Problem Description
I was trying to solve problem ‘1234 - Harmonic Number’, I wrote the following code
long long H( int n ) {
long long res = 0;
for( int i = 1; i <= n; i++ )
res = res + n / i;
return res;
}
Yes, my error was that I was using the integer divisions only. However, you are given n n n, you have to find H ( n ) H(n) H(n) as in my code.
Input
Input starts with an integer T ( ≤ 1000 ) T (≤ 1000) T(≤1000), denoting the number of test cases.
Each case starts with a line containing an integer n ( 1 ≤ n < 231 ) n (1 ≤ n < 231) n(1≤n<231).
Output
For each case, print the case number and H ( n ) H(n) 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
题意:
给出
T
T
T 组数据求出
n
÷
1
+
n
÷
2
⋅
⋅
⋅
⋅
+
n
÷
n
n\div 1+n\div2\cdot \cdot \cdot\ \cdot+n\div n
n÷1+n÷2⋅⋅⋅ ⋅+n÷n的结果;
做题之前先考虑一个问题:
(☄⊙ω⊙ ? ? ? ^{???} ???)☄
看个表再说
被除数 | 12 | 12 | 12 | 12 | 12 | 12 | 12 | 12 | 12 | 12 | 12 | 12 |
---|---|---|---|---|---|---|---|---|---|---|---|---|
序号 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
除数 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
商 | 12 | 6 | 4 | 3 | 2 | 2 | 1 | 1 | 1 | 1 | 1 | 1 |
从表中我们可以观察到 5 5 5 虽然不是 12 12 12 的倍数但是由于计算机本身取整的原理得到 12 ÷ 5 = 2 12\div 5=2 12÷5=2;但是 2 × 6 2\times6 2×6 才是 12 12 12,所以我们用 12 ÷ 2 12\div 2 12÷2 就可以得到 12 12 12 的真正“除数” 6 6 6.。
由此我们也可以观察到,如果 5 5 5 和 6 6 6 之间还有许多整数那么 12 12 12 除去这个数还是为 2 2 2 例如从 7 7 7 到 12 12 12 之间的商始终为 1 1 1;所以我们只需求出能被 12 12 12 整除的数,记录两点之间的数的个数就可以算出 12 ÷ 1 + ⋅ ⋅ ⋅ ⋅ + 1 12\div 1+\cdot \cdot \cdot\ \cdot+1 12÷1+⋅⋅⋅ ⋅+1 的结果了;
根据上面的规律不难得出此题的解题方法
( ′◔ ⊙ \odot ⊙ ◔`)
看代码:
#include<iostream>
using namespace std;
#define ll long long
int main()
{
int t,z=0;
cin>>t;
while(t--)
{
ll n;
cin>>n;
ll sum=0;
ll k=1;//记录上一个能被n整除的数
for(ll i=1; i<=n; i=k+1)
{
k=n/(n/i);//找到能被n整除的位置
sum+=(n/i)*(k-i+1);//把区间的和存入sum
}
cout<<"Case "<<++z<<": "<<sum<<endl;
}
return 0;
}