ZOJ1601:Integer Approximation

本文介绍了一个寻找给定浮点数的最佳整数逼近方法,并提供了一段C++代码实现。该方法通过枚举的方式找到两个整数N和D,使得它们的比例最接近给定的浮点数A,且绝对误差最小。

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 file 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).

Process to the end of file.


Output

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


Sample Input

3.14159265358979
10000


Sample Output

355 113

 

刚刚开始还以为是什么数学知识,原来不是,直接枚举居然也能过。。。

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;

int main()
{
    int m,x,y,l,r;
    double n,minn,t;
    while(~scanf("%lf%d",&n,&m))
    {
        x = y = 1;
        minn = 999999;
        while(x<=m && y<=m)
        {
            t = fabs(n-x*1.0/y);
            if(t<minn)
            {
                l = x;
                r = y;
                minn = t;
            }
            if(x*1.0/y>=n) y++;
            else x++;
        }
        printf("%d %d\n",l,r);
    }
}


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值