Extended Euclidean algorithm ---------------------------- Number theory (template)

Given n pairs of positive integers ai, bi, for each logarithm, find a set of xi, yi such that it satisfies ai ∗ xi + bi ∗ yi = gcd (ai, bi).

Input format The
first line contains the integer n.

Next n lines, each line contains two integers ai, bi.

Output format There are
n lines of output. For each group of ai and bi, find a group of xi and yi that meet the conditions.

The answer to this question is not unique. You can output any xi, yi that meet the conditions.

Data range
1≤n≤105,
1≤ai, bi≤2 ∗ 109
Input sample:
2
4 6
8 18
Output sample:
-1 1
-2 1

注意: gcd(a,0)=a
ax+by=gcd(a,b)
当b=0时
ax=gcd(a,b)=a;
x=1,y=0;
#include<bits/stdc++.h>
using namespace std;
int n;
int a,b;
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 tmp=x;
    x=y;
    y=tmp-a/b*y;
    return d;
}
int main()
{
    cin>>n;
    while(n--)
    {
        cin>>a>>b;
        int x,y;
        exgcd(a,b,x,y);
        cout<<x<<" "<<y<<endl;
    }
}
Published 572 original articles · praised 14 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_43690454/article/details/105248527