一、问题描述
已知两个整数m和n,求mx + ny = gcd(m, n)。
二、知识引入
贝祖定理:m>=0, n>=0, 且m,nZ => E x, y Z, 使 mx + ny =gcd(m,n)
定理证明:1)设m=n=0,则gcd(m, n)=0,显然定理成立。
2)设m != 0 ,集合A={ mx+ny | x, y Z },则 A Z.
=> 令集合P=AN,则P={z | z >= 0 }. 【证明P】
=> 设d是P中最小的正整数,则 E x0, y0 Z , 使 mx0 + ny0 = gcd(m, n) = d.
=> 设d|m = q...r,即m=d*q+r, d>r>=0.
=> r = m - d * q = m - (mx0 + ny0)*q = m(1-x0) - n(qy0)
=> r P, 又d>r与d是P中最小的正整数矛盾
=> r = 0.
=> m=d*q, 同理可证n=d*p,即d是m和n的公约数
=> 设c是m和n的任一公约数,则 m=c*c', n=c*c''.
=> d = mx0 + ny0 = (c*c')x0 + (c*c'')y0 = c ( c'x0 + c''y0 ).
=> d >= c, 即d大于等于m和n的任一公约数
=> d=gcd(m,n)
证明P:
1)设(x, y) = (1,0),则mx+ny = m,即 m A,亦即A中至少有一个正数 |m|.
2)因为P=A N, |m| A, |m| N,所以|m| P. 即P.
P得证。
定理得证。
三、解题思路
已知 mx + ny = gcd(m, n), 且gcd(m, n) = gcd(n, m%n). (m>=n)
=> mx + ny = gcd(m, n) = gcd(n, m%n) = nx' + (m%n)y'
=> mx + ny = nx' + (m%n)y'
=> mx + ny = nx' + (m-n*m/n )y'
=> mx + ny = my' + n(x'-m/ny')
=> x=y', y=x' - m/ny'
=> 即mx + ny = gcd(m,n)的解(x, y),由nx + (m%n)y = gcd(n, m%n)的解(x', y')求出
然后可得出求解递归式:
设求解函数为F(m, n, x, y) : mx + ny = gcd(m, n)
则 F(m, n, x, y) = F(n, m%n, y', x'- m/ny')
F(d, 0, 1, 0): gcd(m,n)=gcd(d,0)=d
四、编程求解
int EuclidXY(int m, int n, int *x, int *y)
{
//欧几里得算法求gcd(m, n),同时求解mx+ny=gcd(m,n)
//递归算法
//输入:两个不全为0的非负整数m,n, 整数x和y的地址
//输出:m,n的最大公约数,gcd(0,0)=0
if(m < n)
{
int temp = n;
n = m;
m = temp;
}
if(n==0)
{
*x = 1;
*y = 0;
return m;
}
//法一
//int r=EuclidXY(n, m%n, x, y);
//int temp = *y;
//*y = *x - m/n * (*y);
//*x = temp;
//法二
int r = EuclidXY(n, m%n, y, x);
*y -= m/n * (*x);
return r;
}
五、推广