Sub topic 6
Handling Zero and Negative Numbers
This chapter assumes you have already read the earlier chapters on the invariant gcd(a, b) = gcd(b, a mod b) and on the iterative and recursive implementations. You should also know how Python's % operator behaves. Those implementations were traced on positive inputs. Real code also receives zeros and negative numbers, and the usual mistakes happen at those boundaries.
What the Definition Says
Recall that d divides n when n = d · k for some integer k. Two facts follow from that definition:
- Every integer divides 0, because 0 = d · 0.
- The divisors of n are the same as the divisors of -n, because n = d · k exactly when -n = d · (-k).
From these two facts we get the working rules:
| Inputs | Result | Reason | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| gcd(a, 0), a ≠ 0 | \ | a\ | Every divisor of a divides 0, and the largest divisor of a is \ | a\ | ||
| gcd(0, 0) | 0 (by convention) | Every integer divides 0, so no largest one exists | ||||
| gcd(-a, b) | gcd(a, b) | Negating a number does not change its divisors | ||||
| Any inputs | Never negative | The GCD is defined as the greatest divisor, and \ | d\ | ≥ d |
Where Signs Go Wrong in the Loop
The invariant gcd(a, b) = gcd(b, a mod b) still holds for negative values. The problem is the remainder's sign. In Python, a % b takes the sign of the divisor b:
print(-48 % 18) # 6
print(48 % -18) # -6C, Java, and JavaScript truncate toward zero instead, so their remainder takes the sign of the dividend. In those languages -48 % 18 is -12. In either convention the loop still terminates, but the value it ends on can be negative. Here is the iterative loop without any sign handling:
def gcd_unsafe(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd_unsafe(-48, 18)) # 6
print(gcd_unsafe(48, -18)) # -6 (wrong sign)
print(gcd_unsafe(-7, 0)) # -7 (wrong sign)Tracing gcd_unsafe(48, -18) shows the problem. The pair (48, -18) becomes (-18, -6), then (-6, 0), and the function returns -6. Every step kept the invariant, but the final value is a divisor of the right size with the wrong sign.
Normalizing the Inputs
There are two simple fixes: take absolute values before the loop, or take the absolute value of the result. The iterative version normalizes first. The recursive version applies abs in its base case.
import math
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
cases = [(48, 18), (-48, 18), (48, -18), (-48, -18),
(0, 7), (7, 0), (0, -7), (0, 0)]
for a, b in cases:
assert gcd(a, b) == gcd_recursive(a, b) == math.gcd(a, b), (a, b)
print(f"gcd({a}, {b}) = {gcd(a, b)}")All eight cases agree with math.gcd. Two of them need no special code:
- gcd(0, 7): the first step swaps the pair to (7, 0), and the next check returns 7.
- gcd(0, 0): b is already 0, so the loop never runs and the function returns 0, which matches the convention.
The Subtraction Method Needs Guards
The subtraction-based version from the earlier chapter assumes a > 0 and b > 0, and that assumption matters. Calling gcd_subtraction(12, 0) loops forever, because subtracting 0 never changes a. Negative inputs either loop forever or drift away from the answer. A safe wrapper normalizes the inputs and handles zero before the loop starts:
def gcd_subtraction_safe(a, b):
a, b = abs(a), abs(b)
if a == 0 or b == 0:
return a + b # gcd(x, 0) = x, and gcd(0, 0) = 0
while a != b:
if a > b:
a -= b
else:
b -= a
return a
print(gcd_subtraction_safe(-12, 0)) # 12
print(gcd_subtraction_safe(-48, 18)) # 6Exercise
Without the call to abs, what does gcd_unsafe(0, -7) return in Python, and what does the normalized gcd(0, -7) return?
Show answer
gcd_unsafe swaps the pair to (-7, 0) and returns -7. The normalized version turns the inputs into (0, 7), swaps them to (7, 0), and returns 7, which is the correct non-negative GCD.
Exercise
Why does the unguarded subtraction method never stop on (12, 0), while the modulo-based loop returns 12 at once?
Show answer
The subtraction loop runs while a != b. Each pass subtracts b = 0 from a, so a stays 12 and the condition never becomes false. The modulo loop checks b != 0 first, sees that b is 0, and returns a = 12 without running a single step.