gcd

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

Description

Returns the greatest common divisor of one or more integers. The greatest common divisor is the largest integer that divides all numbers without a remainder.

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 greatest common divisor.

Code

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

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

   return res
end

return gcd

Examples

local t = require( "tapered" )
local gcd = require( "gcd" )

t.is( 1, gcd( 5, 2 ) )
t.is( 12, gcd( 24, 36 ) )
t.is( 1, gcd( 7, 1 ) )
t.is( 5, gcd( 5, 0 ) )
t.is( 1, gcd( 2, 3, 5 ) )

t.done()

See also