Extended Euclidean algorithm
int ex_gcd(int a, int b,int *x,int *y){
if(!b){
*x = 1;
*y = 0;
return a;
}
int ret = ex_gcd(b, a % b, y, x);
y = y - a / b * x;
}
Proof: //gcd(a,b) is the greatest common divisor of a,b
ax + yb = gcd(a,b) ①
bx' + a%by' = gcd(b,a%b) ②From
a%b = Bringing a / b-b into ②, we get:
bx' + (a / b-b)y' = gcd(b,a%b)
③It is sorted by gcd(b,a%b) = gcd(a,b) ③Get:
ay' + b(x'-(a / b)y') = gcd(a,b)
④So there is almost x = y'; y = x'-(a / b) x;
termination conditions: x = 1 when b = 0; y = 0; gcd(x,y) = a;