PostgreSQL LCM() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL lcm()
function to calculate the least common multiple (LCM) of two or more integers.
Introduction to PostgreSQL LCM function
The least common multiple (LCM) of two integers is the smallest integer that is divisible by each of the numbers.
For example, the LCM of 12 and 18 is 36 because 36 is divisible by 12 and 18.
PostgreSQL 13 or later offers a built-in lcm()
function that calculates the LCM of two integers.
Here’s the syntax of the lcm()
function:
In this syntax, a
and b
are the numbers with types of integer, bigint, and numeric. The lcm()
function returns the LCM of a
and b
.
If either a and b is zero, the lcm()
function returns zero. If a
and/or b
are null, the lcm()
function returns null.
PostgreSQL LCM function examples
Let’s take some examples of using the lcm()
function.
1) Basic PostgreSQL lcm() function example
The following statement uses the lcm()
function to calculate the LCM of two numbers 12 and 18:
Output:
2) Using the lcm() function to find the LCM of three numbers
The following statement uses the lcm()
function to find the LCM of three numbers 12, 18, and 24:
Output:
In this example, we apply the lcm()
function twice:
- lcm(12,18) returns the LCM of 12 and 18, which is 36.
- lcm(lcm(12,18),24) calculates the LCM of the previous LCM (36) and 24, which is 72.
3) Using the lcm() function to find the LCM of multiple numbers
First, create a table called numbers
that have two columns id
and value
:
Second, insert some rows into the numbers
table:
Output:
Third, use a recursive CTE to calculate the LCM of all numbers in the value
column of the numbers
table.
Output:
Defining an aggregate lcm() function
Using a recursive query is quite complicated. Fortunately, PostgreSQL allows you to define a user-defined aggregate function based on the built-in lcm()
function:
You can use the lcm_gg()
function as follows:
Output:
Summary
- Use the
lcm()
function to calculate the least common multiple (LCM) of two or more integers.