Skip to content

Instantly share code, notes, and snippets.

@nskondratev
Last active February 1, 2020 09:56
Show Gist options
  • Save nskondratev/a1e56906b05cd782ae0ded28ebd897aa to your computer and use it in GitHub Desktop.
Save nskondratev/a1e56906b05cd782ae0ded28ebd897aa to your computer and use it in GitHub Desktop.
MySQL Greatest Common Divisor function
CREATE FUNCTION `GCD`(a INTEGER, b INTEGER) RETURNS int(11) DETERMINISTIC
BEGIN
DECLARE dividend INT;
DECLARE divisor INT;
DECLARE remainder INT;
SET dividend := GREATEST(a, b);
SET remainder := LEAST(a, b);
SET divisor := 1;
WHILE remainder != 0 DO
SET divisor = remainder;
SET remainder = MOD(dividend, divisor);
SET dividend = divisor;
END WHILE;
RETURN divisor;
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment