分治算法-近似整数-Integer Approximation poj 1650

Integer Approximation
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 6240 Accepted: 2068
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
翻译:
给定一个浮点数A和一个整数L,求在范围[1,L]内的两个整数n 和 d ,使得n/d能近似等于A,且使误差|A-n/d|最小。


#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;

int L;
double f;
int main(){
	scanf("%lf%d", &f, &L);
	int ansn , ansd;
	int n = 1, d= 1;
	double min1 = 0x3F3F3F3F,cha;
	while(n <= L && d <= L)
	{
		cha = f - (double)n / d;
		if(min1 > fabs(cha))
		{
			min1 = fabs(cha);
			ansn = n; 
			ansd = d;
		}
		if(cha > 0)
		n++;
		else
		d++;
	}
	printf("%d %d\n",ansn,ansd);
	return 0;
} 
发布了430 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zqhf123/article/details/105534970
今日推荐