问题 E: Best Rational Approximation
时间限制: 3 Sec 内存限制: 128 MB
题目描述
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
提示
先码在这,过会再看
据学长说。。法里数列。。。我一开始还以为是沃利斯公式呐
/*2019/8/14/9:37----------------------*/
/*woc我都忘了我还有这么个东西要搞、、、
看这个图,法里数列将0到1之间的任意最简分数表示出来
其中中间一项的分子和分母都是两边的和,即
这正好可以二分,因为从左到右是递增的,所以这题相当于一种另类的二分罢了
*/
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10,mod=1e9+7,inf=0x3f3f3f3f;
int n,m,k,t;
int main(){
int i,j;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("%d ",n);
scanf("%d",&m);
double p;
scanf("%lf",&p);
int xx=0,xy=1,yx=1,yy=1;
while(true)
{
int mx=xx+yx,my=xy+yy;
int gc=__gcd(mx,my);
mx/=gc,my/=gc;
//cout<<mx<<" "<<my<<endl;
//system("pause");
if(my>m)break;
if(1.*mx/my>=p)
yx=mx,yy=my;
else xx=mx,xy=my;
}
if(abs(1.*xx/xy-p)<abs(1.*yx/yy-p))
printf("%d/%d\n",xx,xy);
else printf("%d/%d\n",yx,yy);
}
return 0;
}