Codeforces 854 A Fraction

来源:互联网 发布:黑人 知乎 编辑:程序博客网 时间:2024/06/09 16:32

题目地址
题意:有个人要算出一个不可约分数的值,但是他一不小心吧除号打成了加号得到了一个n,让你求出最大的不可约分数a/b(a+b==n)
思路:因为a+b==n,但是a!=b所以a/b想最大,只能a和b越接近越好,所以从那个值开始出发,a–,b++直到gcd(a,b)==1说明他们是不可约分数就输出。

#include <iostream>#include <cstring>#include <string>#include <queue>#include <vector>#include <map>#include <set>#include <stack>#include <cmath>#include <cstdio>#include <algorithm>#include <iomanip>#define N 1110#define M 555005  #define LL __int64#define inf 0x3f3f3f3f#define lson l,mid,ans<<1#define rson mid+1,r,ans<<1|1#define getMid (l+r)>>1#define movel ans<<1#define mover ans<<1|1using namespace std;const LL mod = 1000000007;int gcd(int x, int y) {    if (!y)        return x;    else        return gcd(y, x%y);}int main() {    cin.sync_with_stdio(false);    int n, a, b;    while (cin >> n) {        if (n % 2) {            a = n / 2;            b = n - a;        }        else {            a = n / 2 - 1;            b = n - a;        }        while (a != 1) {            if (gcd(a, b) == 1) {                break;            }            a--;            b++;        }        cout << a << " " << b << endl;    }    return 0;}
原创粉丝点击