法里数列 Best Rational Approximation

上图 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;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值