UPC 5249 Best Rational Approximation(法里数列+二分)

5249: Best Rational Approximation

时间限制: 3 Sec   内存限制: 128 MB
提交: 287   解决: 20
[ 提交][ 状态][ 讨论版][命题人: admin]

题目描述

Many microcontrollers have no floating point unit but do have a (reasonably) fast integer divide unit. In these cases it may pay to use rational values to approximate floating point constants. For instance,  
355/113 = 3.1415929203539823008849557522124  
is a quite good approximation to  
π = 3.14159265358979323846  
A best rational approximation, p/q, to a real number, x, with denominator at most M is a rational number, p/q (in lowest terms), with q <= M such that, for any integers, a and b with b <= M, and a and b relatively prime, p/q is at least as close to x as a/b:  
|x – p/q|≤|x – a/b|  
Write a program to compute the best rational approximation to a real number, x, with denominator at most M. 

输入

The first line of input contains a single integer P, (1≤P≤1000), which is the number of data sets that follow.  Each data set should be processed identically and independently.  
Each data set consists of a single line of input.  It contains the data set number, K, followed by the maximum denominator value, M (15≤M≤100000), followed by a floating-point value, x, (0≤x < 1). 

输出

For each data set there is a single line of output.  The single output line consists of the data set number, K, followed by a single space followed by the numerator, p, of the best rational approximation to x, followed by a forward slash (/) followed by the denominator, q, of the best rational approximation to x. 

样例输入

3

1 100000 .141592653589793238

2 255 .141592653589793238

3 15 .141592653589793238

样例输出

1 14093/99532

2 16/113

3 1/7


题意 输入一个小数求p/q 为最接近这个小数的p 和 q。



思路 :就是从法里数列中查找距离小数的临界点输出距离小数近的那一个。



代码实现:



#include<bits/stdc++.h>
using namespace std;
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		int k,m;
		double p;
		scanf("%d%d%lf",&k,&m,&p);//.*****浮点读入直接为0.*****; 
		int a=0,b=1,c=1,d=1;
		int mx,my;
		while(1)
		{
			mx=a+c;
			my=b+d;
		//	cout<<mx<<endl<<my<<endl;
			int gc=__gcd(mx,my);
		//	cout<<gc<<endl;
			mx/=gc;my/=gc; //两数互质 除一下gcd即可; 
			if(my>m)
			break;
			//cout<<1.*mx/my<<endl;
			if(1.0*mx/my>=p)//相当于二分 法里数列 从左到右依次递增 二分查找临界值; 
			{
				c=mx;
				d=my;
			}
			else
			{
				a=mx;
				b=my;
			}
		//	cout<<a<<b<<c<<d<<endl;
		}
		cout<<k<<" "; 
		if(abs(1.0*a/b-p)<abs(1.0*c/d-p))
			cout<<a<<"/"<<b<<endl;
		else
			cout<<c<<"/"<<d<<endl;
	}
	return 0;
} 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值