GCD algorithms for a large integers

跟風遠走 提交于 2019-12-04 13:56:05

Knuth explores the GCD at length in The Art of Computer Programming, Volume 2, Section 4.5.2. Knuth gives Algorithm E as the original method of Euclid, Algorithm A as the modern version of Euclid's algorithm, Algorithm B as the binary method and Algorithm L as Lehmer's method, as well as the extended Euclidean algorithm in Algorithm X. I describe (with code) the original Euclidean algorithm, the modern Euclidean algorithm, the binary algorithm, and the extended Euclidean algorithm at my blog.

This paper gives a good description of several versions of Schönhage's algorithms, including code.

thanks a lot for your answer user448810. That binary algorithm is perfect for me and freaking fast. I convert it to non recursive form to save memory and recursion calls. Here is my implementation for my longnum lib, added some rems for lines that are different from standard operators/functions

longnum gcd(longnum x,longnum y)
    {
    x.sig=+1; x.integer(); // x=abs(int(x))
    y.sig=+1; y.integer(); // y=abs(int(y))
    longnum z; int x0,y0,sh=0;
    for (;;)
        {
        if (x.iszero()) { z=y; break; } // if (!x) ...
        if (y.iszero()) { z=x; break; } // if (!y) ...
        x0=x.a[_longnum_a1]&1; // x0=x&1
        y0=y.a[_longnum_a1]&1; // y0=y&1
        if ((!x0)&&(!y0)) { x>>=1; y>>=1; sh++; continue; }
        if (!x0) { x>>=1; continue; }
        if (!y0) { y>>=1; continue; }
        if (x<y) y-=x;
        else     x-=y;
        }
    return (z<<sh);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!