跳到正文

算法·理论

扩展欧几里得定理

small_lemon_qwq约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟

版本

  1. v1当前

可以参考一下这篇博客

  • 前置知识:详解扩展欧几里得定理是用于求方程 ax+by=cax+by=c 的整数解的

欧几里得定理:

对于∀a,b∈N∗,都有gcd⁡(a,b)=gcd⁡(b,amod  b)证明:设a=bp+q,gcd⁡(a,b)=r∴r=gcd⁡(bp+q,b)=gcd⁡(q,b)=gcd⁡(b,q)=gcd⁡(b,amod  b)证毕\text{对于}\forall a,b\in N^*\text{,都有}\gcd(a,b)=\gcd(b,a\mod b)\\\text{证明:设}a=bp+q,\gcd\left(a,b\right)=r\\\therefore r=\gcd\left(bp+q,b\right)=\gcd\left(q,b\right)=\gcd\left(b,q\right)=\gcd\left(b,a\mod b\right)\\\text{证毕}

代码实现:

C++
int gcd(int a,int b){
	if(b==0) return a;
	else return gcd(b,a%b);
}

裴蜀定理:

对于关于x,y的方程ax+by=c:若c   mod gcd⁡(a,b)≠0,则该方程无整数解证明:根据定义,a,b   mod gcd⁡(a,b)=0∴若有整数解,c   mod gcd⁡(a,b)=0∴若c   mod gcd⁡(a,b)≠0,则该方程无整数解证毕\text{对于关于}x,y\text{的方程}ax+by=c:\\\text{若}c\ \ \bmod \gcd(a,b)\not=0,\text{则该方程无整数解}\\\text{证明}:\\\text{根据定义},a,b\ \ \bmod\gcd(a,b)=0\\\therefore \text{若有整数解},c\ \ \bmod \gcd(a,b)=0\\\therefore \text{若}c\ \ \bmod \gcd(a,b)\not=0,\text{则该方程无整数解}\\\text{证毕}

方程ax+by=gcd⁡(a,b)ax+by=\gcd(a,b)的解

众所周知,方程 gcd⁡(a,b)x+0⋅y=gcd⁡(a,b)\gcd(a,b)x+0\cdot y=\gcd(a,b)的解有一组是{x=1y=0\left\{ \begin{matrix} x=1\\ y=0 \end{matrix}\right.(这将是递归出口)

现在假设我们已经求出了方程bx+(amod  b)y=gcd⁡(b,amod  b)bx+(a\mod b)y=\gcd(b,a\mod b)的解为{x=x0y=y0\left\{ \begin{matrix} x=x_0\\ y=y_0 \end{matrix}\right.

那我们应该如何求方程ax+by=gcd⁡(a,b)ax+by=\gcd(a,b)的解呢?

解:根据欧几里得定理,gcd⁡(a,b)=gcd⁡(amod  b)∴bx0+(amod  b)y0=gcd⁡(a,b)∴bx0+(a−⌊a/b⌋×b)y0=gcd⁡(a,b)∴ay0+b(x0−⌊a/b⌋×y0)=gcd⁡(a,b)∴我们可以直接让x=y0,y=x0−⌊a/b⌋×y0\text{解:根据欧几里得定理,}\gcd(a,b)=\gcd\left(a\mod b\right)\\\therefore bx_0+(a\mod b)y_0=\gcd(a,b)\\\therefore bx_0+(a-\lfloor a/b\rfloor\times b)y_0=\gcd(a,b)\\\therefore ay_0+b(x_0-\lfloor a/b\rfloor\times y_0)=\gcd(a,b)\\\therefore \text{我们可以直接让} x=y_0,y=x_0-\lfloor a/b\rfloor\times y_0

代码实现解方程ax+by=gcd⁡(a,b):ax+by=\gcd(a,b):

C++
void exgcd(int a,int b,int &x,int &y){
    if(b==0){
        x=1;
        y=0;
        return;
    }
    exgcd(b,a%b,y,x);
    y-=a/b*x;
}

方程ax+by=cax+by=c的解

假设我们求得方程ax+by=gcd⁡(a,b)ax+by=\gcd(a,b)的解为{x=x1y=y1\left\{ \begin{matrix} x=x_1\\ y=y_1 \end{matrix}\right.,根据裴蜀定理,cc应是gcd⁡(a,b)\gcd(a,b)的倍数,直接让 xx 乘cgcd⁡(a,b)\frac{c}{\gcd(a,b)} 就可以了

代码实现:

C++
#include<bits/stdc++.h>
using namespace std;
int gcd(int a,int b){
	if(b==0){
		return a;
	}else{
		return gcd(b,a%b);
	}
}
void exgcd(int a,int b,int &x,int &y){
    if(b==0){
        x=1;
        y=0;
        return;
    }
    exgcd(b,a%b,y,x);
    y-=a/b*x;
}
int a,b,c;
int main(){
	cin>>a>>b>>c;
	int gcdd=gcd(a,b);
	if(c%gcdd!=0){
		cout<<"原方程无解!";
	}else{
		int x,y;
		exgcd(a,b,x,y);
		cout<<x*c/gcdd<<" "<<y*c/gcdd;
	}
	return 0;
}
原文