lcm

function lcm( x [, ...] ) --> res

Description

Returns the least common multiple of one or more integers. The least common multiple is the smallest integer that is a multiple of all numbers.

Parameters

x

Required number. If the number value is not an integer, it is truncated.

Optional numbers. If any number value is not an integer, it is truncated.

Return Values

res

The least common multiple.

Code

--ZFUNC-lcm-v1
local function lcm( x, ... ) --> res
   local function pgcd( m, n )
      while m ~= 0 do
         m, n = n % m, m
      end
      return n
   end

   local function plcm( m, n )
      if m ~= 0 and n~= 0 then
         return m * n / pgcd( m, n )
      else
         return 0
      end
   end

   local res = math.floor( x )
   for _, n in ipairs{ ... } do
      if n < 0 then return math.sqrt( -1 ) end
      res = plcm( res, math.floor( n ) )
   end

   return res
end

return lcm

Examples

local t = require( "taptest" )
local lcm = require( "lcm" )

t( lcm( 5, 2 ), 10 )
t( lcm( 24, 36 ), 72 )
t( lcm( 2, 3, 5 ), 30 )

t()

See also