Euclidean algorithm and extension algorithm.

Source: Internet
Author: User
Tags gcd greatest common divisor

Baidu Encyclopedia:

Euclidean algorithm, also known as the greatest common divisor method, refers to the calculation of two positive integers, a, B. The fields of application are two aspects of mathematics and computer. The formula GCD (b) = gcd (b,a mod b).

Proof: R = a mod B, a = b * k + r;=> r = A-c * k;d|a && d|b=> (A/D-b/d * k) = R/D=>D|R∴GCD (A, B) = GCD (b, a mod b); code
int gcd (intint  b) {  return0 ? B:GCD (b, a% b);  }

The extended Euclidean algorithm is used to solve a set of X, y in known a, b to satisfy the Bézout equation: ax+by = gcd (A, B) =d (the solution must exist, according to the correlation theorem in number theory). Extended Euclidean is commonly used in solving linear equations and equations. Proof: a*x + b*y = gcd (A, B) b*x + (a mod b) *y = gcd (b, a mod b); gcd (A, b) = gcd (b, a mod b) =>a*x + b*y = b*x + (A-(A/b) *b *y) =>a*x + b*y = a*y + b (x-a/b *y) ∴ There is a set of solutions, x = y; y = x-a/b * y; the solution of XY is based on Abxy, and when a% b = = 0, you can get {x = 0, y = 1} This set of solutions, which is the recursive boundary. Using the computer to solve the code is
#include <iostream>using namespacestd;intgcdintAintb) {    return(a% b = =0? B:GCD (b, a%b));}voidFun (intAintBint&x,int&y) {    if(a% b = =0) {x=0; y =1; return; } fun (b, a%b, x, y); intx1 = x, y1 =y; X=Y1; Y= x1-a/b *Y1; return;}intMain () {intx, y; intA, B;  while(Cin >> a >>b) {Fun (A, B, X, y); cout<<"x ="<< x <<"y ="<< y <<Endl; }    return 0;}

Euclidean algorithm and extension algorithm.

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.