贝祖数

贝祖数

公式:\(ax + by = m (a,b,m \in Z)\) 求x,y

贝祖定理

例:\(2x+y = 3\) 有整数解
因为 2 和 1 的最大公约数是 1
而3是1的整数倍
\(4x+2y = 5\) 无整数解
因为 4 和 2 的最大公约数是 2
而5不是2的整数倍

贝祖数

例:\(104x+40y = 8\)

\[8 = 24-16(1) \\\ = 24-[40 - 16(1)](1) \\\ = 40(-1) + 24(2) \\\ = 40(-1) + [104 - 40(2)] \\\ = 104(2) + 40(-5) \\\ \]

所以x = 2, y = 5

#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, y, x);
    
    y -= a / b * x;
    return d;
}
int main()
{
    int n;
    cin >> n;
    while (n -- )
    {
        int a,b,x,y;
        scanf("%d%d", &a, &b);
        exgcd(a, b, x, y);
        cout << x << ' ' << y << endl;
    }
}
posted @ 2023-02-06 22:24  wqzgg  阅读(145)  评论(0)    收藏  举报