# 贝祖特的身份

11

## Bézout身份简介

## 例子

``````(A, B) -> (u, v)
(42, 12) -> (1, -3)
(4096, 84) -> (4, -195)
(5, 3) -> (2, -3)
(1155, 405) -> (20, -57)
(37377, 5204) -> (4365, -31351)
(7792, 7743) -> (7585, -7633)
(38884, 2737) -> (1707, -24251)
(6839, 746) -> (561, -5143)
(41908, 7228) -> (1104, -6401)
(27998, 6461) -> (3, -13)
(23780, 177) -> (20, -2687)
(11235813, 112358) -> (8643, -864301)
``````

1

# MATL，37 40字节

``````ZdXK2Gw/:1G*1GK/t_w2\$:XI2G*!+K=2#fIb)
``````

### 说明

``````Zd            % implicitly input A and B. Compute their GCD. Call that C
XK            % copy C to clipboard K
2Gw/:         % vector [1, 2, ..., B/C]
1G*           % multiply that vector by A
1GK/t_w2\$:    % vector [-A/C, -A/C+1 ..., A/C]
XI            % copy to clipboard I
2G*           % multiply that vector by B
!+            % all pairwise sums of elements from those vectors
K=2#f         % find row and column indices of sum that equals C
Ib)           % index second vector with column (indexing first vector with
% row is not needed, because that vector is of the form [1, 2, ...])
``````

7

``````a#b=[(u,-v)|v<-[1..],u<-[1..v],gcd a b==u*a-v*b]!!0
``````

3

# Python 3中，101个 106字节

``````def e(a,b):
r=b;x=a;s=z=0;t=y=1
while r:q=x/r;x,r=r,x%r;y,s=s,y-q*s;z,t=t,z-q*t
return y%(b/x),z%(-a/x)``````

``````def e(a, b):
r = b
x = a    # becomes gcd(a, b)
s = 0
y = 1    # the coefficient of a
t = 1
z = 0    # the coefficient of b
while r:
q = x / r
x, r = r, x % r
y, s = s, y - q * s
z, t = t, z - q * t
return y % (b / x), z % (-a / x) # modulus in this way so that y is positive and z is negative``````

@JonathanFrech啊，谢谢！
Sherlock19年

1

# Mathematica，80个字节

``````f@l_:=Mod@@NestWhile[{Last@#,{1,-Quotient@@(#.l)}.#}&,{{1,0},{0,1}},Last@#.l>0&]
``````

``````f[{5, 3}]              (* {2, -3} *)
f[{42, 12}]            (* {1, -3} *)
f[{11235813, 112358}]  (* {8643, -864301} *)
``````

1

# Ruby，83个字节

``->x,y{a=b=0;y.downto(0).map{|u|(-x..0).map{|v|a,b=u,v if u*x+v*y==x.gcd(y)}};p a,b}``

``````def bezout(x,y)
a=b=0
y.downto(0).each do |u|
(-x..0).each do |v|
if u*x + v*y == x.gcd(y)
a,b=u,v
end
end
end
p a,b
end``````

@Bruce_Forte达恩 该测试用例的IRB内存不足。我将尽快编写扩展的欧几里得算法解决方案。
Sherlock9年