LCM

Return the least common multiple of two integers.

Category: numericReturns: INTEGERDialect: PostgreSql

Syntax

LCM(a, b)

Description

## Overview Returns the least common multiple (LCM) of two integers. The LCM is the smallest non-negative integer that is a multiple of both inputs. It is computed using the identity LCM(a, b) = ABS(a * b) / GCD(a, b), which is exact but can overflow when the product ABS(a * b) exceeds the integer type's range. LCM is useful for aligning fractions to a common denominator, for scheduling periodic events with different cycles, and for solving Diophantine equations. ## 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. - LCM(0, n) = 0 and LCM(n, 0) = 0 for all n. - Is symmetric and sign-agnostic. - Raises an error when the intermediate product ABS(a * b) overflows. ## Numeric precision - For values within BIGINT range, LCM is exact. - The intermediate a * b can overflow even when the final LCM fits; consider pre-dividing by GCD: LCM(a, b) = a / GCD(a, b) * b. - LCM does not accept DECIMAL or DOUBLE inputs. ## Compatibility - Matches the PostgreSQL LCM scalar function. - Conforms to the standard mathematical definition of LCM with the LCM(0, n) = 0 convention.

Parameters

NameTypeDescription
aSpecifies the first integer operand. Negative values are accepted; the result uses the absolute values of the inputs.
bSpecifies the second integer operand. Negative values are accepted; the result uses the absolute values of the inputs.

Examples

-- Basic LCM
SELECT LCM(4, 6);  -- 12
-- Coprime numbers: LCM equals their product
SELECT LCM(7, 13);  -- 91
-- LCM with zero is zero by convention
SELECT LCM(0, 5);  -- 0
-- Equal values: LCM equals their absolute value
SELECT LCM(8, 8);  -- 8
-- Negative inputs produce a non-negative result
SELECT LCM(-4, 6);  -- 12
-- NULL propagation
SELECT LCM(NULL, 6);  -- NULL

Pitfalls

See Also

Open in interactive docs →   DeltaForge home →