Euclid Rides… Oh, Not Again! :)

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!

Advertisements

4 thoughts on “Euclid Rides… Oh, Not Again! :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s