算法训练 调和数列问题

Description

输入一个实数x,求最小的n使得,1/2+1/3+1/4+…+1/(n+1)>=x。

输入的实数x保证大于等于0.01,小于等于5.20,并且恰好有两位小数。你的程序要能够处理多组数据,即不停地读入x,如果x不等于0.00,则计算答案,否则退出程序。

输出格式为对于一个x,输出一行n card(s)。其中n表示要计算的答案。

Input

输入描述:
  分行输入x的具体数值
输入样例:
1.00
3.71
0.04
5.19
0.00

Output

输出描述:
  分行输出n的数值,格式为n card(s)
输出样例:
3 card(s)
61 card(s)
1 card(s)
273 card(s)

源码

循环遍历版:

#include <stdio.h>

double calculate(int i)
{
	return 1.0/i;
}

int main()
{
	//freopen("input/thsequence.txt","r",stdin);
	double x;
	while(scanf("%lf",&x)&&x!=0.00)
	{
		double sum=0.0;
		for(int i=2;;i++)
		{
			sum+=calculate(i);
			if(sum>=x)
			{
				printf("%d card(s)\n",i-1);
				break;
			} 
		}
	}
	return 0;
} 

二分版:

#include <stdio.h>

double sum[300];

int bs(double y)
{
	int l=0,r=277,mid;
	while(l<=r)
	{
		mid=(l+r)/2;
		if(sum[mid]<y) l=mid+1;
		else r=mid-1;
	}
	return l;
}

int main()
{
	//freopen("input/thsequence.txt","r",stdin);
	double x=0.0;
	for(int i=2;;i++)
	{
		if(x>5.20) break;
		x+=1.0/i;
		sum[i]=x;
	}
	double y;
	while(scanf("%lf",&y)&&y!=0.0)
	{
		printf("%d card(s)\n",bs(y)-1);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值