C language extended Euclidean algorithm code _c language

Source: Internet
Author: User

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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.