| 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!
October 15, 2009 at 8:42 pm
Changed on the wiki
October 15, 2009 at 9:31 pm
Great!
October 27, 2009 at 4:53 pm
[...] In my previous post I proposed function for GCD calculation. Thus we can calculate LCM either. The only thing we should [...]