Normally we use the extended Euclidean algorithm to calculate pm + qn = gcd (M, n) This expression, generally will choose the recursive way to achieve, because Euclid algorithm recursion depth is only O (LGN), according to lame ' s theorem, So this recursive stack can be ignored.
But in fact, only need to loop to find a set of PM + qn = gcd (M, n) of the expression, the stack depth is kept in O (1), so that the use of function calls in the high-level language to look more complicated, but in the assembly programming is relatively simple.
By assuming that the two numbers in the K-Iteration are M (k) and N (k), we always maintain a cyclic invariant f
F:xm + yn = m (k) and X ' m + y ' n = n (k).
So in the No. 0 step, m (0) = m, n (0) = N, obviously only need x = 1, y = 0, X ' = 0, y ' = 1
Induction: Assuming the K-step operation, x*m + y*n = m (k), X ' m + y ' n = n (k)
and M (k+1) = N (k), can be directly used newx = X ', Newy = y ' get newx*m + newy*n = m (k + 1)
and n (k+1) = m (k) MOD N (k) = m (k)-[M (k)/n (k)]*n (k), we only need to take advantage of x*m + Y*n = m (k) minus X ' m + y ' n = n (k) about the same multiplication [M (k)/n (k)] This elementary school 2-year study of two times Equation Solving (to the point where the linear algebra of the university appears to be called Gaussian elimination) gets a newx ' m + newy ' n = n (k+1), where the operation is omitted.
and then with x = newx, y = newy, x ' = Newx ', y ' = Newy ' replace it to hold the loop invariant.
Finally, at the end of the algorithm, xm + yn = r, x ' m + yn ' = 0
The output of this xm + yn = r is the result we want
How to extend Euclidean algorithm using loop instead of recursive inverse method