Extended Euclidean algorithm

Pseudocode
int egcd( int a,int b; int &X,int &Y ){ if ( b == 0){ X = 1; Y = 0; return a;  } int Xprime,Yprime; int res = egcd(b, a % b, Xprime, Yprime); X = Yprime; Y = Xprime - a / b * Yprime; return res; }

Explanation
Function parameters  are by reference and are used to return values,   are helper variables.All division is integer $${a \over b}=floor({a \over b})$$. The goal of algorithm, is to find $$X$$ and $$Y$$, such that $$aX + bY = gcd(a,b)$$. It works basicaly in the same way as Euclidean algorithm Simply, holds when  , since $$bX^\prime + (a\mod b)Y^\prime = gcd(a,b)$$. From this valus, we can can compute values $$X$$ and $$Y$$, such that $$aX + bY = gcd(a,b)$$. Imagine if we put,
 * When b = 0
 * Otherwise recursion is used, and  and , are comuted such that,

$$X=Y^\prime, Y=X^\prime$$. We would ges such equation $$aX + bY =aY^\prime+bX^\prime = (a \bmod b+{a \over b}bY^\prime + bX^\prime = bX^\prime + (a \bmod b)Y^\prime + ({a \over b}bY^\prime=gcd(a,b)+{a \over b}Y^\prime b$$, importat is that $$aY^\prime+bX^\prime = gcd(a,b)+{a \over b}Y^\prime b $$, where we can move $${a \over b}Y^\prime b$$ to the left side, and then take out $$b$$, to get $$aY^\prime+b(X^\prime-{a \over b}Y^\prime)=gcd(a,b) $$. So if we put $$X=Y^\prime$$ and $$Y=X^\prime-{a \over b}Y^\prime$$, $$aX + bY=gcd(a,b)$$ will hold.