浅谈扩展欧几里得算法

以前写的= = 现在发的原因是 懒得写博客= =

a x + b y = gcd ⁡ ( a , b ) ax+by=\gcd(a,b) ax+by=gcd(a,b)

求满足等式的整数解 x , y x,y x,y

假设 a > b a>b a>b

假设有一组合法解为 x 1 , y 1 x_1,y_1 x1,y1,则有 a x 1 + b y 1 = g c d ( a , b ) ax_1+by_1=gcd(a,b) ax1+by1=gcd(a,b)

由欧几里得算法( gcd ⁡ ( a , b ) = gcd ⁡ ( b , a % b ) \gcd(a,b)=\gcd(b, a\% b) gcd(a,b)=gcd(b,a%b))得

a x + b y = gcd ⁡ ( a , b ) = gcd ⁡ ( b , a % b ) = b x 1 + ( a % b ) y 1 ax + by = \gcd(a,b) = \gcd(b, a\%b) = bx_1 + (a \% b)y_1 ax+by=gcd(a,b)=gcd(b,a%b)=bx1+(a%b)y1

因为 a % b = a − ⌊ a b ⌋ ∗ b a\% b = a - \lfloor\frac{a}{b} \rfloor * b a%b=abab

所以原式可以转化为:

a x + b y = b x 1 + ( a − ⌊ a b ⌋ ∗ b ) y 1 ax+by = bx_1 + (a - \lfloor\frac{a}{b} \rfloor * b)y_1 ax+by=bx1+(abab)y1

a x + b y = b x 1 + a y 1 − ⌊ a b ⌋ b y 1 ax+by=bx_1+ay_1 - \lfloor\frac{a}{b} \rfloor by_1 ax+by=bx1+ay1baby1

a x + b y = a y 1 + b ( x 1 − ⌊ a b ⌋ y 1 ) ax+by=ay_1 + b(x_1-\lfloor\frac{a}{b}\rfloor y_1) ax+by=ay1+b(x1bay1)

由此得

x = y 1 , y = x 1 − ⌊ a b ⌋ y 1 x = y_1,y = x_1 - \lfloor\frac{a}{b} \rfloor y_1 x=y1,y=x1bay1

这样就能得到一组合法解

b = 0 b=0 b=0时 , gcd ⁡ ( a , b ) = a \gcd(a,b)=a gcd(a,b)=a,
此时有唯一的解 : $ x = 1,y = 0$

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

你可能感兴趣的:(浅谈扩展欧几里得算法)