Created
August 11, 2016 01:19
-
-
Save ehmo/9db79b6a4ec72bc18bd238393bf20e5d to your computer and use it in GitHub Desktop.
Fast fibonacci function in pure SQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Fast fibonacci function in pure SQL | |
# Tested on Postgresql 9.5 | |
CREATE OR REPLACE FUNCTION _fib ( | |
n integer, a bigint, b bigint | |
) RETURNS bigint AS $$ | |
BEGIN | |
IF n < 1 THEN | |
RETURN b; | |
END IF; | |
RETURN _fib(n -1, b, a+b); | |
END; | |
$$ LANGUAGE plpgsql; | |
CREATE OR REPLACE FUNCTION fibonacci ( | |
n integer | |
) RETURNS bigint AS $$ | |
BEGIN | |
IF n > 91 THEN | |
RAISE EXCEPTION 'Bigint overflow past fibonacci(91) [%]', n; | |
END IF; | |
RETURN _fib(n, 0, 1); | |
END; | |
$$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment