Given two positive integers m and n, we compute their maximum common factor D and two integers a and B, making A*m+b*n=d
Algorithm Flow
E1. Place a ' =b=1;a=b ' =0;c=m,d=n;
E2. Compute D and R to make C=q*d+r;
E3. If r==0, then exit, there are currently a*m+b*n=d;
E4;c=d;d=r;t=a ' a ' =a;a=t-q*a;t=b '; b ' =b;b=t-q*b; return to E2.
Prove
For the existing M and N, suppose m>n; if the excluding variable a,b,a ', b '; the algorithm is exactly the same as the Euclidean algorithm, which computes the GCD algorithm.
The final requirement is A*M+B*N=D=GCD (m,n); If the formula is set up by Euclidean algorithm, a ' *n+b ' * (m%n) =GCD (n,m%n) can be introduced;
Because GCD (m,n) =GCD (n,m%n);
So a*m+b*n=a ' *n+b ' * (m%n)
=a ' *n+b ' * (M (m/n) *n)
=a ' *n+b ' *m-b ' * (m/n) *n
=b ' *m+ (a '-B ' * (m/n)) *n
So a=b '; B=a '-B ' * (m/n);
can be introduced according to a ', B ' can calculate a, B.
Code implementation
Copy Code code as follows:
void egcd (int m,int N)
{
int a,a1,b,b1,c,d,q,r,t;
A1=b=1,a=b1=0,c=m,d=n;
while (1)
{
q=c/d,r=c%d;
if (r==0)
{
printf ("(%d) *%d+ (%d) *%d=%d\n", a,m,b,n,d);
Return
}
C=d,d=r,t=a1,a1=a,a=t-q*a,t=b1,b1=b,b=t-q*b;
}
}