function ExtendedGCD(A, B: TData; var X, Y: TData): TData; //A*X+B*Y=GCD(A,B)
begin
if B = 0 then
begin
Result := A;
X := 1;
Y := 0;
end
else
begin
Result := ExtendedGCD(B, A mod B, Y, X);
Dec(Y, A div B * X);
end;
end;
求最大公约数
递归(recursion):
function gcd(a,b:longint):longint;
begin
if b=0 then exit(a);
exit(gcd(b,a mod b));
end;
非递归(iterative):
function gcd(a,b:longint):longint;
var t:longint;
begin
while b<>0 do
begin
t:=a;a:=b;b:=t mod b;
end;
exit(a);
end;
或者使用扩展欧几里德算法(辗转相除法):
function extendedEuclid(a,b:longint;
var x,y:longint):longint;
var p,q:longint;
begin
if b=0 then
begin
x:=1;y:=0;exit(a);end;
p:= extendedEuclid (b, a mod b,x,y);
q:=x;x:=y;y:=q-a div b *y;
exit(p);
end;
求最小公倍数
k:=a*b div gcd(a,b);