Created
November 3, 2022 07:13
-
-
Save sgsfak/4b0cfdbc4e67595764efb8654a7f6cac to your computer and use it in GitHub Desktop.
Compute "deserium" numbers in SQL
This file contains hidden or 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
CREATE OR REPLACE FUNCTION deserium(num INTEGER) RETURNS BOOLEAN AS $$ | |
WITH RECURSIVE | |
digts(d, m, pos) AS ( | |
SELECT t / 10, t % 10, 1 FROM (VALUES(num)) v(t) | |
UNION ALL | |
SELECT d / 10, d % 10, pos + 1 | |
FROM digts WHERE d > 0 | |
), | |
to_sum(v) AS ( | |
SELECT m ^ (MAX(pos) over () - pos + 1) FROM digts | |
) | |
SELECT sum(v) :: int = num | |
FROM to_sum; | |
$$ LANGUAGE SQL IMMUTABLE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment