Return the greatest common divisor of two integers (non-negative, using the Euclidean algorithm).
GCD(a, b)
## Overview Returns the greatest common divisor (GCD) of two integers. The GCD is the largest non-negative integer that divides both inputs exactly. GCD is computed with the Euclidean algorithm, which runs in O(log(min(a, b))) time and is numerically exact. GCD is a foundational primitive for reducing fractions to lowest terms, computing LCMs, and performing modular arithmetic. It is symmetric (GCD(a, b) = GCD(b, a)) and sign-agnostic (GCD(-a, b) = GCD(a, b)). ## Behavior - Accepts INTEGER or BIGINT for both arguments. - Returns a non-negative integer of the promoted common type. - Returns NULL if either argument is NULL. - GCD(0, n) returns |n| and GCD(n, 0) returns |n|. - GCD(0, 0) returns 0 by convention. - Is symmetric and sign-agnostic. ## Numeric precision - For INTEGER and BIGINT, GCD is exact. - The Euclidean algorithm does not overflow for values within the integer type's range. - GCD does not accept DECIMAL or DOUBLE inputs; cast to INT if your values are integer-valued floats. ## Compatibility - Matches the PostgreSQL GCD scalar function. - Conforms to the standard mathematical definition of GCD.
| Name | Type | Description |
|---|---|---|
a | Specifies the first integer operand. Negative values are accepted; the result uses the absolute values of the inputs. | |
b | Specifies the second integer operand. Negative values are accepted; the result uses the absolute values of the inputs. |
-- Basic GCD
SELECT GCD(12, 8); -- 4
-- Coprime numbers
SELECT GCD(7, 13); -- 1
-- GCD with zero is the absolute value of the other argument
SELECT GCD(0, 5); -- 5
-- Negative inputs produce a non-negative result
SELECT GCD(-12, 8); -- 4
-- Both zero by convention is zero
SELECT GCD(0, 0); -- 0
-- NULL propagation
SELECT GCD(NULL, 12); -- NULL