-1

This is the problem in my textbook:

Greatest Common Divisor of two integers, p and q
(a) Base Case. If p = q: return p.
(b) p < q. If p < q: return GCD(q, p).
(c) p > q. If p > q: return GCD(p, p - q)

It seems as though my solution matches the above statements. But it generates a recursion error:

  File "G:\python\function.py", line 8, in GCD
    return GCD(p,p-q)
RuntimeError: maximum recursion depth exceeded

My code:

def GCD(p,q):
    """Greatest Common Divisor of two integers, p and q."""
    if q == p:
        return p
    elif p < q:
        return GCD(q,p)
    elif p > q:
        return GCD(p,p-q)
GCD(21,28)

Didn't I follow the statements of the problem?

BBedit
  • 7,037
  • 7
  • 37
  • 50
  • 1
    Your textbook has got it wrong; rule *(c)* ensures that `p` is forever greater that `q`, and you enter into an infinite loop. – Martijn Pieters Mar 15 '14 at 18:35
  • In case you were wondering, greatest common divisors are in the standard library: `__import__('fractions').gcd(21, 28)`. Also, I'm pretty sure that after the first `return`, you could do `return GCD(p, p % q)` if you have your heart set on recursion. Your textbook is definitely wrong, as Martijn said, and I think it meant to say `p % q` where it said `p -q`. – anon582847382 Mar 15 '14 at 18:38

1 Answers1

0

It should be mod the smaller of the two in the last step. So:

def GCD(p,q):
    """Greatest Common Divisor of two integers, p and q."""
    if p == q or q==0:
        return p
    elif p > q:
        return GCD(q,p) # ensure p < q
    return GCD(p,q%p) 
assert GCD(21,28) == 7
assert GCD(28,21) == 7
assert GCD(3,12) == 3
assert GCD(16,12) == 4
frmdstryr
  • 20,142
  • 3
  • 38
  • 32