Search code examples
pythonalgorithmcomputer-science

Implementing Extended Euclid Algorithm


Why is the following implementation of the Extended Euclid Algorithm failing?

def extended_euclid(a,b):
    if b == 0:
        return {a, 1, 0}

    d1,x1,y1 = extended_euclid(b, a % b)
    d = d1
    x = y1
    y = x1 - math.floor(a/b) * y1
    return {d, x, y} 

Solution

  • This is the implementation found in https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm , looks similar to your's one.

    def egcd(a, b):
        if a == 0:
            return (b, 0, 1)
        else:
            g, x, y = egcd(b % a, a)
            return (g, y - (b // a) * x, x)