GCD algorithm:
Seek greatest common divisor by dividing
#include <stdio.h>int gcd (int a,int b) { return a%b==0?b:gcd (b,a%b);} int main () { printf ("%d", gcd (15,18)); return 0;}
Extended GCD algorithm:
For a nonnegative integer that is not exactly 0, a, a, if gcd (A, A, A, b) represents A/b greatest common divisor, there must be an integer pair of x, Y, which makes ax+by = GCD (A, B).
Set
AX1+BY1=GCD (A, B),
BX2+A%BY2=GCD (B,A%B)
Because GCD (A, B) =gcd (b,a%b), so
Ax1+by1
=bx2+a%by2
=bx2+ (a-a/b*b) y2
=ay2+ (x2-a/b*y2) b
So X1=y2,y1=x2-a/b*y2
And a set of solutions for the IF (b==0) indeterminate equation is x=1,y=0
So the extended GCD code is:
#include <stdio.h> #define LL long Longll exgcd (ll a,ll b,ll &x,ll &y) { if (b==0) {X=1;y=0;return A;} ll R=EXGCD (b,a%b,x,y); ll Tmp=x;x=y;y=tmp-a/b*y; return r;} int main () { ll a,b,ans,x,y; scanf ("%lld%lld", &a,&b); ANS=EXGCD (a,b,x,y); printf ("(%LLD) * (%LLD) + (%LLD) * (%LLD) =%lld", A,x,b,y,ans); return 0;}
Extended Euclidean algorithm