POJ 1650 Integer Approximation (追赶法求解)

Integer Approximation
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 5458 Accepted: 1806

Description

The FORTH programming language does not support floating-point arithmetic at all. Its author, Chuck Moore, maintains that floating-point calculations are too slow and most of the time can be emulated by integers with proper scaling. For example, to calculate the area of the circle with the radius R he suggests to use formula like R * R * 355 / 113, which is in fact surprisingly accurate. The value of 355 / 113 ≈ 3.141593 is approximating the value of PI with the absolute error of only about 2*10 -7. You are to find the best integer approximation of a given floating-point number A within a given integer limit L. That is, to find such two integers N and D (1 <= N, D <= L) that the value of absolute error |A - N / D| is minimal.

Input

The first line of input contains a floating-point number A (0.1 <= A < 10) with the precision of up to 15 decimal digits. The second line contains the integer limit L. (1 <= L <= 100000).

Output

Output file must contain two integers, N and D, separated by space.

Sample Input

3.14159265358979
10000

Sample Output

355 113



题意:在L的范围内寻找两个数N ,D,使得fabs(A-N/D)最小


思路:看到别人用的追赶法,看了一下解释,写了一下,复杂度O(n)


总结:也想过二分枚举,但是T了



ac代码:

#include<stdio.h>
#include<math.h>
#include<string.h>
#include<stack>
#include<queue>
#include<vector>
#include<iostream>
#include<algorithm>
#define MAXN 60100
#define LL long long
#define ll __int64
#define INF 0xfffffff
#define mem(x) memset(x,0,sizeof(x))
#define PI acos(-1)
#define mod 1000000007
using namespace std;
double a;
double dis(int n,int d)
{
	return a-(double)n/d;
}
int main()
{
	while(scanf("%lf",&a)!=EOF)
	{
		int l;
		scanf("%d",&l);
		int d=1,n=1;
		int ansd=d,ansn=n;
		double mi=INF*1.0;
		while(d<=l&&n<=l)
		{
			double k=dis(n,d);
			//printf("%lf\n",k);
			double kk=fabs(k);
			if(kk<mi)
			{
				mi=kk;
				ansd=d;
				ansn=n;
			}
			if(k>0)
			n++;
			else
			d++;
		}
		printf("%d %d\n",ansn,ansd);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值