[FT][2]codevs 2190 有理逼近

2190 有理逼近
时间限制: 1 s
空间限制: 32000 KB
题目等级 : 黄金 Gold
题解
查看运行结果
题目描述 Description
对于一个素数P,我们可以用一系列有理分数(分子、分母都是不大于N的自然数)来逼近sqrt(p),例如P=2,N=5的时候:1/1 < 5/4 < 4/3 < sqrt(2) < 3/2 < 5/3 < 2/1。
任 务 :
给定P、N(N>sqrt(p)),求X、Y、U、V,使x/y < sqrt(p) < u/v且x/y与sqrt(p)之间、sqrt(p)与u/v之间都不能再插入满足题意的有理分数。

输入描述 Input Description
输入文件的第一行为P、N

输出描述 Output Description
输出文件只有一行,格式为“X/Y U/V”。注意,答案必须是既约的,也就是说分子、分母的最大公约数必须等于1。

样例输入 Sample Input
样例1:
2 5
样例2:
5 100

样例输出 Sample Output
样例1:
4/3 3/2

样例2:
38/17 85/38

数据范围及提示 Data Size & Hint
P、N<30000


【分析】
枚举分母,二分分子…


【代码】

//有理逼近 
#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define M(a) memset(a,0,sizeof a)
#define fo(i,j,k) for(i=j;i<=k;i++)
using namespace std;
const int mxn=1e6;
int n,p;
double d,x;
int a[mxn];
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
inline int gcd(int x,int y) {if(x%y==0) return y;return gcd(y,x%y);}
inline void yue(int &zi,int &mu)
{
    int tmp=gcd(zi,mu);
    zi/=tmp,mu/=tmp;
}
int main()
{
    int i,j;
    p=read();n=read();
    double d=sqrt(p);
    int x1=1,x2=1,y1=30000,y2=1,mu;
    fo(mu,1,n)  //枚举分母 
    {
        int l=1,r=n;
        while(l<r)
        {
            int mid=(l+r)/2;
            double tmp=(double)mid/(double)mu;
            if(tmp>d) r=mid;
            else l=mid+1;
        }
        double tmp=(double)l/(double)mu;
        if(tmp<(double)y1/(double)y2 && tmp>d) y1=l,y2=mu;
        if(tmp>(double)x1/(double)x2 && tmp<d) x1=l,x2=mu;
        tmp=(double)(l-1)/(double)mu;
        if(tmp>(double)x1/(double)x2 && tmp<d) x1=l-1,x2=mu;
        if(tmp<(double)y1/(double)y2 && tmp>d) y1=l,y2=mu;
        yue(x1,x2);yue(y1,y2);
    }
    printf("%d/%d %d/%d\n",x1,x2,y1,y2);
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值