Sub topic 6
Handling Zero and Negative Numbers
This chapter assumes you have read the earlier chapters. You should know the invariant gcd(a, b) = gcd(b, a mod b) and be able to read the iterative and recursive Python versions of Euclid's algorithm. You also need to know that % in Python is the remainder operator. Up to now the inputs have been positive integers. Real code gets zeros, negative values, and sometimes values that aren't integers at all. This chapter defines what the answer should be in each case, shows where naive code goes wrong, and gives a version you can test against the standard library.
What the GCD Should Return
The definition says the greatest common divisor is the largest integer that divides both inputs. Applied literally, that definition leaves some cases unclear. Mathematicians and standard libraries resolve them with a small set of conventions.
The result is never negative
If d divides a, then -d also divides a. The divisors of 12 are ±1, ±2, ±3, ±4, ±6, and ±12. The largest of these is always positive, so the GCD is defined to be non-negative. The sign of the inputs also has no effect on the result:
gcd(a, b) = gcd(|a|, |b|)
This holds because a and -a have exactly the same divisors. So gcd(-48, 18), gcd(48, -18), and gcd(-48, -18) all equal 6.
Zero is divisible by everything
Every integer d divides 0, because 0 = d × 0. The common divisors of a and 0 are therefore just the divisors of a, and the largest of those is |a|. This gives the base case the algorithm already uses:
gcd(a, 0) = |a|
The special case gcd(0, 0)
When both inputs are zero, every integer is a common divisor, so no largest one exists. The literal definition breaks down here. The standard convention is gcd(0, 0) = 0. Three reasons support it:
- Order the integers by divisibility, so that "x is below y" means x divides y. Then the GCD is the greatest lower bound, and 0 sits at the top of that order because everything divides it. The greatest lower bound of 0 and 0 is 0.
- The formula gcd(a, 0) = |a| gives 0 when a = 0, so the base case needs no exception.
- Bézout's identity, covered in a later chapter, says the GCD is the smallest non-negative value of a·x + b·y. With a = b = 0, the only such value is 0.
Python agrees: math.gcd(0, 0) returns 0.
| Inputs | Result | Reason | Column | Column |
|---|---|---|---|---|
| gcd(12, 18) | 6 | Ordinary case | ||
| gcd(-12, 18) | 6 | Sign is ignored | ||
| gcd(-12, -18) | 6 | Sign is ignored | ||
| gcd(7, 0) | 7 | Everything divides 0 | ||
| gcd(-7, 0) | 7 | gcd(a, 0) = \ | a\ | |
| gcd(0, 0) | 0 | Convention | ||
| gcd(1, n) | 1 | 1 has no other divisors |
How Python's `%` Treats Negative Numbers
Euclid's algorithm is only as well behaved as the remainder operator it runs on, and remainders of negative numbers differ between languages.
Python uses floored division. a // b rounds toward negative infinity, and a % b is defined so that a == (a // b) * b + a % b. As a result, the remainder always has the same sign as the divisor b, and its absolute value is less than |b|.
C, C++, Java, JavaScript, Go, and Rust use truncated division. The quotient rounds toward zero, and the remainder takes the sign of the dividend a.
| Expression | Python (floored) | C / Java (truncated) |
|---|---|---|
| 7 % 3 | 1 | 1 |
| -7 % 3 | 2 | -1 |
| 7 % -3 | -2 | 1 |
| -7 % -3 | -1 | -1 |
Both conventions guarantee |a mod b| < |b|. Termination depends only on that property, so Euclid's loop terminates with negative inputs in every language. Only the sign of the answer is at risk.
Where Naive Code Goes Wrong
Here is the loop with the abs call removed:
def gcd_naive(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd_naive(-48, 18)) # 6
print(gcd_naive(48, -18)) # -6
print(gcd_naive(-48, -18)) # -6
print(gcd_naive(-7, 0)) # -7Trace gcd_naive(48, -18) to see why the result is negative:
- 48 % -18 = -6, because 48 // -18 = -3 and 48 - (-3)(-18) = 48 - 54 = -6. The pair becomes (-18, -6).
- -18 % -6 = 0. The pair becomes (-6, 0).
- The loop stops and returns -6.
The magnitude is correct. The sign is wrong. In Python, every remainder takes the sign of the current divisor. After the first step, every value in the pair therefore has the sign of the original b. The naive loop returns ±gcd with the sign of b, or a itself when b is 0.
With truncated remainders the sign is harder to predict. The helper below copies C's % exactly, using integer arithmetic only, so you can watch the effect from inside Python:
def trunc_mod(a, b):
# Remainder with the sign of the dividend, like C and Java
r = abs(a) % abs(b)
return r if a >= 0 else -r
def gcd_c_style(a, b):
while b != 0:
a, b = b, trunc_mod(a, b)
return a
print(gcd_c_style(-48, 18)) # 6
print(gcd_c_style(48, -18)) # -6
print(gcd_c_style(-48, -18)) # -6For (-48, 18), the remainders are -12 and then 6, so the sign flips during the loop. The lesson is the same in every language: normalize the sign explicitly instead of relying on how % behaves.
Two Correct Fixes
Normalize at the start
The iterative version from the earlier chapter applies abs before the loop:
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return aWith both values non-negative, every remainder is non-negative, so the loop only ever sees natural numbers. This is the easiest version to reason about. It is also the one to port to other languages, because floored and truncated remainders agree when both operands are non-negative.
Normalize at the end
The recursive version applies abs only in the base case:
def gcd_recursive(a, b):
if b == 0:
return abs(a)
return gcd_recursive(b, a % b)
print(gcd_recursive(48, -18)) # 6
print(gcd_recursive(0, 0)) # 0This works because the invariant gcd(a, b) = gcd(b, a mod b) holds up to sign for any remainder convention: the pair keeps the same set of common divisors at every step. Taking the absolute value once at the end fixes the sign. The one drawback is that intermediate values can be negative. That makes the code harder to read and easier to break if someone later adds an optimization that assumes non-negative values.
Zero Inside the Loop
Zero also comes up in a few smaller cases.
- Zero as the first argument. gcd(0, 5) runs one iteration: 0 % 5 = 0, so the pair becomes (5, 0) and the result is 5. Nothing special is needed.
- Zero as the second argument. The loop condition
b != 0is false immediately, so the function returnsabs(a). The guard also preventsa % 0, which would raiseZeroDivisionError. - Order of the arguments. If a < b, the first iteration swaps them, because a % b = a. You never need to sort the inputs first.
Gotchas Beyond Python
Overflow when taking the absolute value
Python integers have unlimited size, so abs always works. In C and Java, a 32-bit int ranges from -2³¹ to 2³¹ - 1, and abs(INT_MIN) overflows. Java's Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE, which is still negative. Even a correctly normalized routine cannot return gcd(-2³¹, 0) = 2³¹ in that type. The usual fixes are to compute with a wider or unsigned type, or to document that the result for this input is undefined. Java's BigInteger.gcd and C++17's std::gcd show how libraries handle this: std::gcd declares the behavior undefined when |m| or |n| cannot be represented.
Non-integer inputs
The hand-written function also accepts floats, with misleading results. gcd(0.3, 0.1) does not return 0.1, because 0.3 % 0.1 is about 0.09999999999999998 in binary floating point. The loop then keeps going on tiny rounding errors until it reaches a meaningless value. math.gcd rejects floats with TypeError. If your function is called from outside your own code, validate the input in the same way:
def gcd_checked(a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("gcd requires integers")
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return aNote that bool is a subclass of int in Python, so gcd_checked(True, 4) returns 1, the same as math.gcd(True, 4).
More than two arguments
Since Python 3.9, math.gcd accepts any number of arguments, and math.gcd() with no arguments returns 0. That result follows from gcd(0, x) = |x|: 0 is the identity element for the GCD, the way 0 is for addition. If you fold your own two-argument function over a list, start from 0 and the empty-list case works with no extra code:
from functools import reduce
def gcd_many(*values):
return reduce(gcd, values, 0)
print(gcd_many()) # 0
print(gcd_many(-12, 18, 30)) # 6Testing Against the Standard Library
Edge cases are where hand-written versions fail, so test them directly. The script below checks fixed boundary cases, then random signed pairs. For each pair it confirms agreement with math.gcd, a non-negative result, and that the result divides both inputs:
import math
import random
def gcd(a, b):
a, b = abs(a), abs(b)
while b != 0:
a, b = b, a % b
return a
cases = [(0, 0), (0, 5), (5, 0), (-5, 0), (0, -5),
(-48, 18), (48, -18), (-48, -18), (1, -1), (-1, -1)]
for _ in range(10000):
cases.append((random.randint(-10**9, 10**9), random.randint(-10**9, 10**9)))
for a, b in cases:
g = gcd(a, b)
assert g == math.gcd(a, b), (a, b, g)
assert g >= 0
if g != 0:
assert a % g == 0 and b % g == 0
print("all", len(cases), "cases passed")Run the same script with gcd_naive in place of gcd, and it fails on the first input where b is negative.
Exercise
Without running it, what does gcd_naive(-30, -12) return in Python, and why? Trace each pair.
Show answer
It returns -6. First, -30 % -12 = -6, because -30 // -12 = 2 and -30 - 2(-12) = -6. The pair becomes (-12, -6). Next, -12 % -6 = 0, so the pair becomes (-6, 0) and the loop returns -6. Every remainder has the sign of the divisor, which is negative here, so the result is the negative of the true GCD, 6.
Exercise
A colleague says gcd(0, 0) should raise an error because "every integer divides 0, so there is no greatest common divisor." Give two concrete reasons to return 0 instead.
Show answer
First, returning 0 is consistent with the base case gcd(a, 0) = |a| for every a, including a = 0, so the algorithm needs no special branch. Second, 0 is the identity for the GCD, since gcd(0, x) = |x|. That makes folds over lists work, including the empty list, which is why math.gcd() returns 0. There is also a mathematical reason: in the divisibility order, 0 is the greatest element, so the greatest lower bound of 0 and 0 is 0. Bézout's identity also gives 0 as the smallest non-negative value of 0·x + 0·y.
Exercise
You port the recursive version (abs only in the base case) to Java using int. Which input still gives a wrong answer, and what would you do about it?
Show answer
Any input whose final value is Integer.MINVALUE, such as gcd(Integer.MINVALUE, 0) or gcd(Integer.MINVALUE, Integer.MINVALUE). The true answer is 2^31, which int cannot represent, and Math.abs(Integer.MINVALUE) returns Integer.MINVALUE, which is negative. Fixes include computing in long (or as unsigned values) and returning a long, rejecting that input explicitly, or documenting the result as undefined, as C++17's std::gcd does.