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( "taptest" ) local gcd = require( "gcd" ) t( gcd( 5, 2 ), 1 ) t( gcd( 24, 36 ), 12 ) t( gcd( 7, 1 ), 1 ) t( gcd( 5, 0 ), 5 ) t( gcd( 2, 3, 5 ), 1 ) t()