Skip to content

Instantly share code, notes, and snippets.

@emchateau
Forked from CliffordAnderson/euclid.xqy
Created May 20, 2020 23:58
Show Gist options
  • Save emchateau/8de5eb6757ef774c73d589685d294b46 to your computer and use it in GitHub Desktop.
Save emchateau/8de5eb6757ef774c73d589685d294b46 to your computer and use it in GitHub Desktop.
The Euclidean Algorithm in XQuery
xquery version "3.1";
(: The Euclidean algorithm calculates the lowest common denominator of two integers :)
declare function local:euclid($num1 as xs:integer, $num2 as xs:integer) as xs:integer*
{
if ($num1 > $num2) then local:euclid($num2, $num1 - $num2)
else if ($num2 > $num1) then local:euclid($num1, $num2 - $num1)
else $num1
};
local:euclid(13,8)
xquery version "3.1";
(: The Eculidean algorithm by division and remainder method -- much faster !:)
declare function local:gcd($num1 as xs:integer, $num2 as xs:integer) as xs:integer*
{
if ($num1 > $num2 and $num1 mod $num2 != 0) then local:gcd($num2, $num1 mod $num2)
else if ($num2 > $num1 and $num2 mod $num1 != 0) then local:gcd($num1, $num2 mod $num1)
else $num2
};
local:gcd(13,8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment