From c691cc98e31e52982a79ffc10b8e91e8c700592b Mon Sep 17 00:00:00 2001 From: ame Date: Fri, 8 Dec 2023 12:33:33 -0600 Subject: lcm --- src/math.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ src/math.h | 11 +++++++++++ src/reg.c | 5 +++++ 3 files changed, 64 insertions(+) create mode 100644 src/math.c create mode 100644 src/math.h (limited to 'src') diff --git a/src/math.c b/src/math.c new file mode 100644 index 0000000..3e36e3b --- /dev/null +++ b/src/math.c @@ -0,0 +1,48 @@ +/*local function gcd(a,b) + if b == 0 then return a end + return gcd(b, math.fmod(a, b)) +end + +local function lcm(a) + local out = a[1] + + for i=2,#a do + out = ((a[i] * out)) / (gcd(a[i], out)) + end + return out +end +*/ +#include "math.h" +#include "stdint.h" +#include + +uint64_t gcd(uint64_t a, uint64_t b){ + if(b == 0) return a; + return gcd(b, a % b); +} + +uint64_t lcm(uint64_t* a, size_t len){ + uint64_t out = a[0]; + + for(size_t i = 1; i != len; i++){ + out = (a[i] * out) / gcd(a[i], out); + } + return out; +} + +int l_lcm(lua_State* L){ + luaL_checktype(L, 1, LUA_TTABLE); + size_t len = lua_objlen(L,1); + uint64_t* nums = malloc(sizeof * nums * len); + for(size_t i = 0; i <= len-1; i++){ + + lua_pushinteger(L,i+1); + lua_gettable(L,1); + + nums[i] = luaL_checknumber(L, -1); + lua_pop(L,1); + } + lua_pushnumber(L, lcm(nums, len)); + free(nums); + return 1; +} diff --git a/src/math.h b/src/math.h new file mode 100644 index 0000000..cfce896 --- /dev/null +++ b/src/math.h @@ -0,0 +1,11 @@ +#include "lua.h" + +int l_lcm(lua_State*); +int l_gcd(lua_State*); + +static const luaL_Reg math_function_list [] = { + {"lcm",l_lcm}, + //{"gcd",l_gcd}, + + {NULL,NULL} +}; diff --git a/src/reg.c b/src/reg.c index 50dc8b9..e443cae 100644 --- a/src/reg.c +++ b/src/reg.c @@ -2,6 +2,7 @@ #include "table.h" #include "crypto.h" #include "io.h" +#include "math.h" int luaopen_llib(lua_State* L) { lua_newtable(L); @@ -18,6 +19,10 @@ int luaopen_llib(lua_State* L) { lua_newtable(L); luaL_register(L, NULL, io_function_list); lua_setfield(L, 2, "io"); + + lua_newtable(L); + luaL_register(L, NULL, math_function_list); + lua_setfield(L, 2, "math"); //make llib global lua_setglobal(L, "llib"); return 1; -- cgit v1.2.3