上图 0/1和1/1(左边) 以及中间的是法里数列
分母分子互质;
0 1 ①
0 1/2 1 ②
0 1/3 1/2 2/3 1 ③
0 1/4 1/3 1/2 2/3 3/4 1 ④
0 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 1 ⑤ ....
题目大意:给个小数p(0<=p<1),
求差值与其最小的不可约分分数且分母不能超过n
思路: 二分法里数列
#include <iostream>
#include <algorithm>
#include <math.h>
#define STD std::ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
int main()
{
STD;
int t;
int nu,n;
double p;
cin>>t;
while (t--)
{
cin>>nu>>n>>p;
//cout<<nu<<" "<<n<<" "<<p<<endl;
int x1=0,y1=1,x2=1,y2=1;
int x3,y3;
while (1)
{
x3=x1+x2;
y3=y1+y2;
int gc=__gcd(x3,y3);
x3/=gc;
y3/=gc;
if (y3>n)
break;
if ((1.0*x3/y3)<=p)
{
y1=y3;
x1=x3;
}
else
{
x2=x3;
y2=y3;
}
}
cout<<nu<<" ";
if (fabs(1.0*x1/y1-p)>fabs(1.0*x2/y2-p))
cout<<x2<<"/"<<y2<<endl;
else
cout<<x1<<"/"<<y1<<endl;
}
return 0;
}