标签:
扩展欧几里德算法:
已知a, b求解一组x,y,使它们满足等式: ax+by = gcd(a, b) =d(解一定存在,根据数论中的相关定理)。
扩展欧几里德常用在求解模线性方程及方程组中。
证明:
ax+by=gcd(a,b);
1. (1) a = 0,ax+by = gcd(a,b) = gcd(0,b) = b,
此时x = 0(此时x的值是任意的),y = 1;
(2)b = 0, ax + by = gcd(a,b) = gcd(a,0) = a,
此时x = 1,y = 0(此时y的值是任意的);
2.a和b都不为0时
ax1 + by1 = gcd(a, b)
由欧几里德定理:gcd(a,b) = gcd(b, a%b)得
ax1 + by1 = gcd(a,b) = gcd(b, a%b) 即:
bx2 + a%by2 = gcd(b, a%b) = ax1 + by1
a % b = a - a/b*b;
ax1 + by1 = bx2 + (a - a/b*b)y2;
=bx2 + ay2 - a/b*b*y2;
=ay2 + b(x2-a/b*y2);
所以:x1 = y2, y1 = x2 - a/b*y2
扩展欧几里德算法代码:
void gcd(int a, int b, int &x, int &y) { if(b == 0) { x = 1; y = 0; r = a;//r为a、b的最大公约数 return ; } gcd(b, a%b, x, y); int t = x; x = y; y = t - a / b * y; }
标签:
原文地址:http://www.cnblogs.com/qq2424260747/p/4909455.html