问题:对于正整数a,b,求整数x,y满足:
ax+by=gcd(a,b)
解法:ExtandedGCD
已知gcd(a,b)=gcd(b,a mod b);
设gcd(a,b)=d
假设已求出x1,y1满足bx1+(a mod b)y1=d(*)
因为a mod b=a-(a div b)*b(**)
(**)代入(*)得:
ay1+(x1-(a div b)*y1)b=d
所以x=y1
y=x1-(a div b)*y1.
递归求解直到b=0返回(x=1,y=0)即可
Code:
1: Program ExtandedGCD;
2:
3: var
4: a,b,x,y : longint;
5:
6: Function ExtGCD(a,b:longint;var x,y:longint):longint;
7: var
8: t : longint;
9: begin
10: if b=0 then
11: begin
12: ExtGCD:=a;
13: x:=1;
14: y:=0;
15: exit;
16: end;
17: ExtGCD:=ExtGCD(b,a mod b,x,y);
18: t:=x;
19: x:=y;
20: y:=t-(a div b)*y;
21: end;
22:
23: begin
24: readln(a,b);
25: writeln(ExtGCD(a,b,x,y));
26: writeln(x,' ',y);
27: end.