How to extend Euclidean algorithm using loop instead of recursive inverse method

Source: Internet
Author: User
Tags gcd

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.