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;
}