Codeforces Round #172 (Div. 2) B. Nearest Fraction 二分

B. Nearest Fraction

Time Limit: 20 Sec

Memory Limit: 256 MB

题目连接

http://codeforces.com/contest/281/problem/B

Description

You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction  whose denominator is no more than n.

Formally, you should find such pair of integers a, b (1 ≤ b ≤ n; 0 ≤ a) that the value  is as minimal as possible.

If there are multiple "nearest" fractions, choose the one with the minimum denominator. If there are multiple "nearest" fractions with the minimum denominator, choose the one with the minimum numerator.

Input

A single line contains three integers x, y, n (1 ≤ x, y, n ≤ 105).

Output

Print the required fraction in the format "a/b" (without quotes).

Sample Input

3 7 6

Sample Output

2/5

HINT

 

题意

给你a,b,n,让你找一个分数出来,使得其分母不大于n,并且这个分数最接近a/b的最简分数

题解:

直接暴力枚举分母,然后再二分分子就好了

然后更新答案

代码

#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;

int gcd(int a,int b)
{
    return b==0?a:gcd(b,a%b);
}
int main()
{
    int a,b,n;
    cin>>a>>b>>n;
    if(n>=b)
    {
        printf("%d/%d\n",a/gcd(a,b),b/gcd(a,b));
        return 0;
    }
    double x = a*1.0 / b*1.0;
    int ans1 = 0,ans2 = 1;
    for(int i=1;i<=n;i++)
    {
        int l = 0,r = 100000;
        while(l<=r)
        {
            int mid = (l+r)/2;
            if(mid*1.0/(i*1.0)>=x)r=mid-1;
            else l=mid+1;
        }
        if(fabs((l-1)*1.0/(i*1.0)-x)<fabs((ans1*1.0)/(ans2*1.0)-x))
            ans1 = l-1,ans2 = i;
        if(fabs((l)*1.0/(i*1.0)-x)<fabs((ans1*1.0)/(ans2*1.0)-x))
            ans1 = l,ans2 = i;
    }
    printf("%d/%d\n",ans1/gcd(ans1,ans2),ans2/gcd(ans1,ans2));
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值