Number Theory - Extended Euclidean exgcd

ALGORITHM

We would like to obtain a set of \ (x, y \) makes

\(ax+by = \gcd(a,b)\)

according to

\(\gcd(a,b) = \gcd(b,a\bmod b)\)

If we now have \ (x ', y' \ ) makes

\(bx'+(a\bmod b)y' = \gcd(b,a\bmod b)\)

Then

\(ax+by = bx'+( a-\lfloor\frac a b\rfloor b)y'\)

After transposition


\(ax+by = ay'+b(x'-\lfloor\frac a b\rfloor y')\)

We can get a particular solution set

\ (X = y ', y = x' - \ lfloor \ frac ab \ rfloor and '\)

Recursive solution, when \ (b = 0 \) time, \ (X =. 1, Y = 0 \) ;

template

int exgcd(int a,int b,int &x,int &y)
{
    if(b==0)
    {
        x = 1; y = 0;return a;
    }
    int x1,y1;
    int ans = exgcd(b,a%b,x1,y1);
    x = y1;
    y = x1-(a/b)*y1;
    return ans;
}

example

https://www.luogu.com.cn/problem/P1082

Reference blog

https://www.zybuluo.com/samzhang/note/541890

Guess you like

Origin www.cnblogs.com/hezongdnf/p/12076931.html