RealPhobia HDU - 4180


RealPhobia HDU - 4180 

Bert is a programmer with a real fear of floating point arithmetic. Bert has quite successfully used rational numbers to write his programs but he does not like it when the denominator grows large. Your task is to help Bert by writing a program that decreases the denominator of a rational number, whilst introducing the smallest error possible. For a rational number A/B, where B > 2 and 0 < A < B, your program needs to identify a rational number C/D such that:
1. 0 < C < D < B, and
2. the error |A/B - C/D| is the minimum over all possible values of C and D, and
3. D is the smallest such positive integer.

The input starts with an integer K (1 <= K <= 1000) that represents the number of cases on a line by itself. Each of the following K lines describes one of the cases and consists of a fraction formatted as two integers, A and B, separated by “/” such that:
1. B is a 32 bit integer strictly greater than 2, and
2. 0 < A < B

For each case, the output consists of a fraction on a line by itself. The fraction should be formatted as two integers separated by “/”.

Sample Input

3
1/4
2/3
13/21 

Sample Output

1/3
1/2
8/13


   题意:  给你一个分数a/b ,让你找到一个c/d 满足 a/b-c/d 最小。

  

  思路: 扩展欧几里得

  对于 a ==1  显然  c/d=  a/(b-1);

  其他情况:  | a/b-c/d |= |(ad-bc)|/bd   

  考虑  d 满足 b>d  ,  考虑分子  |ad-bc|  最小等于 1; 那么就是解方程,  用扩欧得到  d , c  的值,因为有两种情况,即 ad-bc=1 |  bc-ad=1;  所以我们需要都算出来,比较  d  ,取 d 大 的那个。

  对于 gcd( a , b )!=1  直接除以  gcd(a,b)   输出就行。



#pragma comment(linker, "/STACK:1024000000,1024000000")
//#include <bits/stdc++.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<algorithm>
#define maxn 10010
#define INF 0x3f3f3f3f
#define eps 1e-8
#define MOD 1000000007
#define ll long long
using namespace std;

int ex_gcd(int a,int b,int &x,int &y)
{
    if(!b)
    {
        x=1;
        y=0;
        return a;
    }
    int d=ex_gcd(b,a%b,y,x);
    y-=a/b*x;
    return d;
}
int main()
{
    int a;
    int b;
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d/%d",&a,&b);
        if(a==1)
        {
            printf("%d/%d\n",a,b-1);
            continue;
        }
        int x,y;
        int d=ex_gcd(a,b,x,y);
        if(d!=1)
        {
            printf("%d/%d\n",a/d,b/d);
            continue;
        }
        int a1=(x+b)%b;
        int a2=(-x+b)%b;
        int b1=(-y+a)%a;
        int b2=(y+a)%a;
        if(a1>a2)
            printf("%d/%d\n",b1,a1);
        else
            printf("%d/%d\n",b2,a2);
    }
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值