拓展欧几里得

题目

Now tell you two nonnegative integer \(a\) and \(b\). Find the nonnegative integer \(X\) and integer \(Y\) to satisfy \(X*a + Y*b = 1\). If no such answer print "sorry" instead.

Input
The input contains multiple test cases.
Each case two nonnegative integer \(a,b (0<a, b\le 2^{31})\)
Output
output nonnegative integer \(X\) and integer \(Y\), if there are more answers than the \(X\) smaller one will be choosed. If no answer put "sorry" instead.

题解

推导过程

对于 \(ax+by=1\) 的理解:

\(t = \gcd(a,b)\)
那么 \(a = ut, b = vt\) , 很容易知道 \(u\) , \(v\) 互质,即 \(\gcd(u, v) = 1\)
既然 \(u\) , \(v\) 互质,下面来证明一个定理:

    对于线性方程 \(ax + by = 1\), (\(x\), \(y\)未知),若该方程有整数解,那么\(a\), \(b\)互质
用反证法即可证明
不妨设 \(\gcd(a, b) = h(h > 1)\) ,那么必然有互质的两个数 \(u\), \(v\) ,使得 \(a = hu\) , \(b = hv\) ,代入原方程
    \(hux+hvy = 1\)
=>   \(ux+vy\) = \(\frac{1}{h}\)(分数)
由于 \(u\) , \(v\) , \(x\) , \(y\) 都是整数,那么 \(\frac{1}{h}\) 也必为整数,矛盾
原命题得证

所以  \(ux + vy = 1\)
两边同乘以\(t  utx + vty = t\)
变形      \(ax + by = \gcd(a,b)\)

我们知道 \(a\%b\)\(a-(a/b)*b\) 等价
既然已经证明了 \(ax + by = \gcd(a,b)\) 存在整数解
又因为 \(\gcd(a,b) = \gcd(b,a \% b)\)
所以得连等式  \(bx_0 + (a\%b)y_0 = \gcd(b, a\%b) = \gcd(a, b) = ax + by\)
带入 \(a\%b = a-(a/b)*b\)
移项      \(b*( x_0 - (a/b)y_0 ) + ay_0 = ax + by\)
对应系数相等,所以
      \(x = y_0\)
      \(y = x_0 - (a/b)*y_0\)
若要求最小正整数解
只需  \(x += b\)
同时  \(y -= a\)
因为,\(a(x+b)+b(y-a)=ax+by\) ,又化到原来的方程,与原来的方程是等价的。
设该方程的一个特解为 \(x=x_0,y=y_0\) ,于是可以得到一个解系:

\[x=x_0+kb\\ y=y_0-ka \]

其中 \(k\in Z\)

AC代码

#include <iostream>
using namespace std;
int exgcd(int a, int b, int & x, int & y)
{
    if(!b) {
        x = 1;
        y = 0;
        return a;
    }
    int d = exgcd(b, a % b, x, y);
    int t = x;
    x = y;
    y = t - (a / b) * y;
    return d;
}
int main()
{
    int a, b;
    while(cin >> a >> b) {
        int x = 0, y = 0;
        int d = exgcd(a, b, x, y);
        if (d != 1)
            cout << "sorry" << endl;
        else {
            while(x <= 0) {
                x += b;
                y -= a;
            }
            cout << x << " " << y << endl;
        }
    }
    return 0;
}
posted @ 2020-01-27 13:35  xDaniel  阅读(189)  评论(0)    收藏  举报