Integer Approximation
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 5801 | Accepted: 1957 |
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
Source
Northeastern Europe 2001, Far-Eastern Subregion
题意概括:输入一个浮点数, 再输入某范围内的两个整数, 求某范围内能够使这个浮点数减去两个整数商的差的绝对值最小。求这两个整数各是多少。
解题思路:这个题可以使用“追赶法”。 即设k为差,kk为差的绝对值,每一次此次若kk小于前一次的kk, 则更新kk,以及两个整数的值。 然后,如果k为整数,则意味着两个数的商太小,可以尝试增加被除数的值,即被除数进行累加(被除数进行追赶);反之,若k为负数,则意味着两个数的商太大,可以尝试增加除数的值,即除数进行累加(除数进行追赶)。直到被除数或除数中的一个大于所规定的范围,循环结束。输出两个整数,这两个整数就是所求的整数。
AC代码:
鄙视自己一下。。。。
题意概括:输入一个浮点数, 再输入某范围内的两个整数, 求某范围内能够使这个浮点数减去两个整数商的差的绝对值最小。求这两个整数各是多少。
解题思路:这个题可以使用“追赶法”。 即设k为差,kk为差的绝对值,每一次此次若kk小于前一次的kk, 则更新kk,以及两个整数的值。 然后,如果k为整数,则意味着两个数的商太小,可以尝试增加被除数的值,即被除数进行累加(被除数进行追赶);反之,若k为负数,则意味着两个数的商太大,可以尝试增加除数的值,即除数进行累加(除数进行追赶)。直到被除数或除数中的一个大于所规定的范围,循环结束。输出两个整数,这两个整数就是所求的整数。
AC代码:
#include<stdio.h>
#include<math.h>
double A;
double dis(int n, int d)
{
return A - (double)n / d;
}
int main(void)
{
double k, kk, min = 999999 * 1.0;
int L;
int n, d, p, q;
scanf("%lf", &A);
scanf("%d", &L);
n = 1;
d = 1;
p = n;
q = d;
while(n <= L && d <= L)
{
k = dis(n, d);
kk = fabs(k);
if(kk < min)
{
min = kk;
p = n;
q = d;
}
if(k > 0)
{
n ++;
}
else
{
d ++;
}
}
printf("%d %d\n", p, q);
return 0;
}
错误原因:此题未看题解前无思路。
![鄙视](http://static-blog.csdn.net/xheditor/xheditor_emot/default/despise.gif)