Question

I looking for the information about fast GCD computation algorithms. Especially, I would like to take a look at the realizations of that.

The most interesting for me: - Lehmer GCD algorithm, - Accelerated GCD algorithm, - k-ary algorithm, - Knuth-Schonhage with FFT. I have completely NO information about the accelerated GCD algorithm, I just have seen a few articles where it was mentioned as the most effective and fast gcd computation method on the medium inputs (~1000 bits)

They looks much difficult for me to understand from the theory view. Could anybody please share the code (preferable on c++) with realization of any algorithm\parts from the list or share any experience of doing this. I will be also appreciate for any information, comments, advice, places to look into. I have a class to work with big integers, but I have no methods to work with it. Except, for sure, Euclid and Binary gcd algorithms, which is looks clear to me for now; there is no problems with it. The main thing I would like to get in the end: the code of realization lehmer gcd. (it is the easier from the list)

Was it helpful?

Solution

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.

OTHER TIPS

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);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top