First, Euclidean algorithm: That is, the greatest common divisor method, used to find two integers, a, b
See: Greatest Common divisor templates
Second, extended Euclidean algorithm: for a non-total 0 nonnegative integer A,B,GCD (A, a, a, a, a, b) greatest common divisor, there must be an integer pair x, y, making gcd (A, b) =ax+by.
kb2.3 extended Euclidean algorithm (solution for AX+BY=GCD and inverse element)
#include <iostream>#include<stdio.h>using namespacestd;//returns D=GCD (A, b), and corresponding to x, y in equation Ax+by=dLong LongEXTEND_GCD (Long LongALong LongBLong Long&x,Long Long&y) { if(a==0&&b==0)return-1;//no greatest common divisor if(b==0) {x=1; y=0;returnA;} Long LongD=EXTEND_GCD (b,a%b,y,x); Y-=a/b*x; returnD;}//Seeking Inverse element//ax=1 (mod n)Long LongMod_reverse (Long LongALong LongN) { Long Longx, y; Long LongD=EXTEND_GCD (a,n,x,y); if(d==1)return(x%n+n)%N; Else return-1;}intMain () {Long LongA,b,x,y; scanf ("%lld%lld",&a,&b); Long LongD=EXTEND_GCD (a,b,x,y); printf ("%lld x=%lld y=%lld\n", D,x,y); return 0;}
View Code
14 Euclid, extended Euclidean algorithm template