Harmonic Number (II)(数论)
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).OutputFor each case, print the case number and H(n) calculated by the code.
我试图解决“1234-谐波数”的问题,我写了下面的代码
long long H( int n ) {
long long res = 0;
for( int i = 1; i <= n; i++ )
res = res + n / i;
return res;
}
是的,我的错误是我只使用整数除法。但是,你得到了n,你必须在我的代码中找到H(n)。
输入
输入以整数T(≤1000)开始,表示测试用例的数量。
每种情况都以包含整数n(1≤n<231)的行开始。
输出
对于每个案例,打印案例编号和由代码计算的H(n)。
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
题意:
给出了一段代码,并说明是错误的,让求n/i的前n项羽和;
思路:
将 (n/i)看成f(x)=n/x,x∈N,这个函数是关于y=x对称,对称点为(根号n,根号n),只需要计算n/x的前sqrt(n)和,用for循环计算,完成后将结果乘2,因为对称点只有一个,所以减去一个对称点的f(sqrt(n))值;
代码
#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
int n,t=0;
scanf("%d",&n);
while(n--)
{
long long n,i,s=0,l;
scanf("%lld",&n);
l=sqrt(n);
for(i=1; i<=l; i++)
s=s+n/i;
s=s*2-l*l;
printf("Case %d: %lld\n",++t,s);
}
return 0;
}