note This article available in Russian.

Continuing the idea outlined earlier I would like to offer my version of the GCD function.

CREATE OR REPLACE FUNCTION gcd(bigint, bigint) RETURNS bigint AS
$BODY$
 WITH RECURSIVE t(a, b) AS (
	VALUES (abs($1) :: bigint, abs($2) :: bigint)
UNION ALL
	SELECT b, mod(a,b) FROM t
	WHERE b > 0
)
SELECT a AS gcd FROM t WHERE b = 0;
$BODY$
IMMUTABLE
STRICT
LANGUAGE SQL;

BTW, I believe this version should be available in the PostgreSQL Wiki instead of David Fetter’s one (David, with all respect! It was inspired by yours.). ;)

“Why?” — you may ask.

  • It is much, much faster;
  • It handles negative numbers properly;
  • Because I wish to make this world better! :)

Cheers! Don’t do drugs!