LCM using SQL

David Fetter wrote a post about GCD calculations using SQL.

Reading this post I remembered my university years and course of number theory in particular. It’s still impossible to forget Mrs. Alexeeva’s lectures. Who knows her will understand what I mean. 🙂

Anyway. In my previous post I proposed function for GCD calculation. Thus we can calculate LCM either. The only thing we should recall that

LCM(a,b) · GCD(a,b) = |a · b|
LCM(a,b) = |a · b| ÷ GCD(a,b)

However, I suggest you to change formula a bit to

LCM(a,b) = |a| ÷ GCD(a,b) · |b|

This is the correct change because GCD is the divisor for both numbers. This will reduce the required storage needed for intermediate result.

CREATE OR REPLACE FUNCTION lcm(bigint, bigint)
  RETURNS bigint AS
  SELECT $1 / gcd($1, $2) * $2;

PS. gcd(bigint, bigint) function declaration was in my previous post.