跳到正文

算法·理论

扩展欧几里得

#SUSPENDED#约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年1月20日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟
获赞
2

版本

  1. v1当前

定义:

扩展欧几里得算法是欧几里得算法(又叫辗转相除法)的扩展, 其目的是为了找到一个整数解关于未知数 xx 和 yy 的线性同余方程 ax+by=cax+by=c 的整数解。

推理过程:

ax1+by1=gcd(b,a mod b)ax_1+by_1=gcd(b,a\bmod b)

bx2+(a mod b)y2=gcd(b,a mod b)bx_2+(a\bmod b)y_2=gcd(b,a\bmod b)

由欧几里得定理可知:gcd(a,b)=gcd(b,a mod b)gcd(a,b)=gcd(b,a\bmod b)

∴ax1+by1=bx2+(a mod b)y2\therefore ax_1+by_1=bx_2+(a\bmod b)y_2

∵a mod b=a−⌊ab⌋×b\because a\bmod b=a-\lfloor\frac{a}{b}\rfloor\times b

∴ax1+by1=bx2+(a−⌊ab⌋×b)y2\therefore ax_1+by_1=bx_2+(a-\lfloor\frac{a}{b}\rfloor\times b)y_2

∴ax1+by1=ay2+bx2−⌊ab⌋×by2\therefore ax_1+by_1=ay_2+bx_2-\lfloor\frac{a}{b}\rfloor\times by_2

∴ax1+by1=ay2+b(x2−⌊ab⌋y2)\therefore ax_1+by_1=ay_2+b(x_2-\lfloor\frac{a}{b}\rfloor y_2)

∴x1=y2,y1=x2−⌊ab⌋y2\therefore x_1=y_2, y_1=x_2-\lfloor\frac{a}{b}\rfloor y_2

将 x2x_2 , y2y_2 不断代入递归求解直到 b=0b=0 ,递归 x=1x=1 , y=0y=0 回去求解。

代码实现:

C++
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;
}
原文