How to implement a recursive MDC calculation algorithm in Python?

2

The non-recursive version is below:

def mdc(a,b):
    while b !=0:
        resto = a % b
        a = b
        b = resto

    return a

print(mdc(50,2))

A recursive attempt would be:

def mdc(a, b):
    if b == 0:
        return a
    resto = a % b
    a = b
    b = resto
    return mdc(a, b)  

What do you think? Any other solution?

    
asked by anonymous 19.04.2018 / 15:23

2 answers

6

The non-recursive solution could be rewritten as:

def mdc(a, b):
    while b:
        a, b = b, a % b
    return a

print(mdc(70, 25)) # 5

See working at Repl.it | Ideone | GitHub Gist

The recursive version could be rewritten as:

def mdc(a, b):
    return a if not b else mdc(b, a % b)

print(mdc(70, 25)) # 5

See working at Repl.it | Ideone | GitHub Gist

But the simplest solution is the native function:

from fractions import gcd

print(gcd(70, 25)) # 5

See working at Repl.it | Ideone | GitHub Gist

    
19.04.2018 / 20:54
3

Hello, this seems to be all right here. Just a little information is that in python instead of:

a = b
b = resto

One could write:

a,b = b,resto

And I personally prefer to use the recursive version as I find it easier to debug. And I think there is no other simple way, like those presented, to implement this algorithm.

    
19.04.2018 / 19:28