i try calculate recusively gcd of several numbers.
here try. more numbers 2 erverlasting loop. i'm not sure pgcd( unpack(arg)) part, have no idea of else.
edit in fact, seems arg.n >2 not efficient...
function pgcd ( ... ) local arg = table.pack(...) if arg.n >2 local tmp = table.remove(arg,1) return pgcd (tmp, pgcd( unpack(arg) )) else a,b = unpack(arg) repeat , b = b , % b until % b == 0 return b end end print (pgcd(18,12)) -- works fine print (pgcd(18,12,9)) -- everlasting loop
in fact endding test testing once far.
function pgcd ( ... ) local arg = table.pack(...) if arg.n > 2 local tmp = table.remove(arg,1) return pgcd (tmp, pgcd( unpack(arg) ) ) else a,b = unpack(arg) repeat , b = b , math.fmod(a,b) until b == 0 -- test once far return end end print (pgcd(18,12)) -- works fine print (pgcd(18,12,6)) -- works fine
Comments
Post a Comment