lightoj1234——调和级数+欧拉常数

题目链接:http://lightoj.com/volume_showproblem.php?problem=1234

In mathematics, the nth harmonic number is the sum of the reciprocals of the first n natural numbers:

In this problem, you are given n, you have to find Hn.

Input

Input starts with an integer T (≤ 10000), denoting the number of test cases.

Each case starts with a line containing an integer n (1 ≤ n ≤ 108).

Output

For each case, print the case number and the nth harmonic number. Errors less than 10-8 will be ignored.

Sample Input

12

1

2

3

4

5

6

7

8

9

90000000

99999999

100000000

Sample Output

Case 1: 1

Case 2: 1.5

Case 3: 1.8333333333

Case 4: 2.0833333333

Case 5: 2.2833333333

Case 6: 2.450

Case 7: 2.5928571429

Case 8: 2.7178571429

Case 9: 2.8289682540

Case 10: 18.8925358988

Case 11: 18.9978964039

Case 12: 18.9978964139

 

题目翻译:

求1/n+2/n+3/n+....+n/n的值,保证误差不小于1e-8;

可以用公式来求(可以百度一下),比较直接,不过需要自己再补一个误差值(1.0/2*n)。

#include<iostream>
#include<cmath>
using namespace std;
const double r=0.57721566490153286060651209;     //欧拉常数
const int maxn=1e4;
double sum[maxn];
void init(){
	sum[1]=1.0; 
	for(int i=2;i<=maxn;i++)
		sum[i]=sum[i-1]+1.0/i;
}
int main(){
	int T,n;
	scanf("%d",&T);
	init();
	for(int kcase=1;kcase<=T;kcase++){
		scanf("%d",&n);
		if(n>maxn){
			double ans=log(n)+r+1.0/(2*n);
			printf("Case %d: %.10lf\n",kcase,ans);
		}
		else printf("Case %d: %.10lf\n",kcase,sum[n]);
	}
	return 0;
}

最简单的方法是每隔50个存储一个值(保证不会超时),然后在求的时候,找到最近的一个存储的值,从这个值开始递推求最终值。(跑一个网上的代码实现)

#include <iostream>
#include <cstdio>
using namespace std;
#define MAX 100000000
double ans[2000100];
int main()
{
    int t,n,k;
    int casenum;
    casenum=0;
    double sum=0.0;
    k=0;
    ans[0]=0;
    for(int i=1;i<=MAX;i++)
    {
        sum+=1.0/i;
        if(i%50==0)
        {
            ans[++k]=sum;
        }
    }
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int num=n/50;
        double s;
        s=ans[num];
        for(int i=50*num+1;i<=n;i++)
            s+=1.0/i;
        printf("Case %d: %.10lf\n",++casenum,s);
    }
    return 0;

}

其实我自己最初写的代码,感觉也是可以AC的(但是不知道为啥子WA了?QAQ),也很好理解,就是对前1e6的用前缀和维护,判断给的数是否大于1e6,如果大于就递推求,感觉不会超时,也不会炸,但是不知道就是过不了(在炸和超时之间转换),有知道的可以评论一下我。万分感激!!!

错误代码如下:

#include<iostream>
using namespace std;
const int maxn=1e6;
double sum[maxn];
void init(){
	sum[1]=1.0; 
	for(int i=2;i<=maxn;i++)
		sum[i]=sum[i-1]+1.0/i;
}
int main(){
	int T,n;
	scanf("%d",&T);
	init();
	for(int kcase=1;kcase<=T;kcase++){
		scanf("%d",&n);
		if(n>maxn){
			double ans=sum[maxn];
			for(int i=maxn+1;i<=n;++i)
				ans+=1.0/i;
			printf("Case %d: %.10f\n",kcase,ans);
		}
		else printf("Case %d: %.10f\n",kcase,sum[n]);
	}
	return 0;
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值