46 lines
974 B
Lua
46 lines
974 B
Lua
--- Math utilities.
|
|
-- @module advtrains_doc_integration.mathutils
|
|
-- @alias M
|
|
local M = {}
|
|
|
|
local function gcdmain(x, y, ...)
|
|
if y == nil then
|
|
return x or 1
|
|
end
|
|
y = y%x
|
|
if y == 0 then
|
|
return gcdmain(x, ...)
|
|
end
|
|
return gcdmain(y, x, ...)
|
|
end
|
|
|
|
--- Compute the greatest common divider.
|
|
-- Note that the behavior of this function is undefined if the arguments
|
|
-- include infinity or NaN.
|
|
-- @tparam integer ... The numbers used for the computation.
|
|
-- @treturn integer The GCD of the given numbers.
|
|
function M.gcd(...)
|
|
local args = {...}
|
|
for k, v in pairs(args) do
|
|
if v == 0 then
|
|
return 0
|
|
elseif v ~= v then
|
|
return v
|
|
elseif v < 0 then
|
|
args[k] = -v
|
|
end
|
|
end
|
|
return gcdmain(unpack(args))
|
|
end
|
|
|
|
--- Reduce a fraction.
|
|
-- @tparam integer num The numerator.
|
|
-- @tparam integer denom The denominator.
|
|
-- @treturn int,int The reduced fraction.
|
|
function M.reduce_fraction(num, denom)
|
|
local gcd = M.gcd(num, denom)
|
|
return num/gcd, denom/gcd
|
|
end
|
|
|
|
return M
|