1 概述
扩展欧几里得算法 用来 求解一组x,y,使它们满足贝祖等式: ax+by = gcd(a, b) =d(已知a, b, 且该解一定存在)。扩展欧几里德常用在求解模线性方程及方程组中。
2 欧几里得算法 (又称辗转相除法)
int gcd(int a, int b)
{
if (a < b)
{
int c = a;
a = b;
b = c;
}
if (b == 0)
return a;
else
return gcd(b, a%b);
}
2 扩展欧几里得
如果 b == 0, x = 1, y = 0, 使得 a = ax + by
如果 b != 0, 则 gcd 首先计算出满足 dd = gcd(b, a%b)和 dd = b*xx + (a%b)*yy
有 d = gcd(a, b) = dd = gcd(b, a%b)
==> d = b*xx + (a - b * (a/b))yy = a*yy + b*(xx - (a/b)*yy)
则对应过来有:x = yy, y = xx - (a/b)*yy
int e_gcd(int a, int b, int &x, int &y)
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
else
{
int cx, cy, d;
d = e_gcd(b, a%b, cx, cy);
x = cy;
y = cx - (a/b)*cy;
return d;
}
}