算法要求:
Given two positive integers m and n, we compute their greatest common divisor d,and we also compute two not-necessarily-positive integers a and b such that am + bn = d.
对于给定的两个正整数 m 和 n,我们能得到两者的GCD---d,同样的我们也能计算得到,满足 am + bn = d 中的两个整数 a 和 b。
描述1:
E1:[Initialize.] Set a'<-b<-1,a<-b'<-0,c<-m,d<-n;
E2:[Divide] Let q and r be the quotiend and remainder, respectively, of c divided by d.
(We have c = qd +r and 0<= r <d.)
E3:[Remainder zero?] If r = 0, the algorithm terminates; we have in this case am + bn = d as desired.
E4:[Recycle.] Set c<-d, d<-r, t<-a', a'<-a, a<-t-qa, t<-b',b'<-b, b<-t-qb, and back to E2.||
描述2:
int Extended_Eucild_algorithm(int *a,int *b,int m,int n)
{
int ta=1,tb=0;
int q=m/n,r=m%n;
*a=0,*b=1;
while(r!=0)
{
m=n;
n=r;
int tmp=ta;ta=*a;*a=tmp-*a*q;//注意*a表示值
tmp=tb;tb=*b;*b=tmp-*b*q;
q=m/n;r=m%n;
}
return n;
}
对于已知非负整数 m 和 n解求 a * m + b * n =GCD(a , b)。
1、当 n = 0 时,GCD(m ,n)= m,则 a = 1 ,b = 0 ;
2、当 n != 0 时,GCD(m , n)= GCD(n , m%n),其中 m%n = m - m/n*n(/ 取整数部分) ,
a1 * m + b1 * n = GCD(m , n), a2 * n + b2 * (m%n)= GCD(n , m%n),
a1 * m + b1 * n =
a2 * n + b2 * (m%n)=
a2 * n + b2 *
(
m - m/n*n
),
整理得
a1 * m + b1 * n = b2 * m + (a2 - m/n * b2)
*
n,
则解得 a1 = b2;b1 =
a2 - m/n * b2 。
Extended Eucild's algorithm的相关信息:
https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
递归实现该算法: