Euclidean algorithm, also known as the greatest common divisor method, is used to calculate two integers, a, b, and so on.
Basic algorithm: Set A=qb+r, where a,b,q,r are integers, then gcd (A, B) =gcd (b,r), gcd (A, B) =gcd (b,a%b).
The first kind of proof:
A can be expressed as A = kb + R, then r = a mod b
Assuming D is a number of conventions for a, B, there are
D|a, d|b, and r = a-kb, so d|r
So d is the number of conventions (B,a mod b)
Assuming D is the number of conventions (B,a mod b), then
D | B, D |r, but a = KB +r
So d is also the number of conventions (A, B)
therefore (b) and (b,a mod b) The number of conventions is the same, and their greatest common divisor are necessarily equal, to be certified
The second kind of proof:
To be certified Euclidean algorithm is established, namely: GCD (A, B) =gcd (b,r), where GCD is to take greatest common divisor meaning, r=a mod b
The following certificate gcd (A, B) =gcd (B,R)
Set C is the greatest common divisor of a, B, C=GCD (A, B), there is A=MC,B=NC, where m,n is a positive integer, and m,n are prime numbers
by r= a mod B, r= a-qb which, q is a positive integer,
Then r=a-qb=mc-qnc= (M-QN) c
B=nc,r= (M-QN) C, and N, (M-QN) coprime (assuming n,m-qn not coprime, N=xd, m-qn=yd where x,y,d are positive integers, and d>1
Then a=mc= (qx+y) DC, B=XDC, at this time a B greatest common divisor into DC, with the premise contradiction,
So n, m-qn must coprime)
Then GCD (b,r) =C=GCD (A, B)
Evidence.
The implementation of the algorithm:
The simplest method is to apply a recursive algorithm, the code is as follows:
1 int gcd ( int A,int b)2 {3 if(b==0 )4 return A; 5 return 6 GCD (b,a%b); 7 }
The code can be optimized as follows:
1 int gcd (int A,int b)2 {3 return b? gcd (b , a%B): A; 4 }
Of course, you can also use an iterative form:
1 intGCD (intAintb)2 { 3 while(b! =0) 4 { 5 intR =b;6b = a%b;7A =R;8 } 9 returnA;Ten}
Euclid algorithm (Euclidean method)