a code that finds common divisors of two numbers
1 Like
Shouldn’t you be using google instead of the dev forum for this sort of question?
Pretty sure most math questions have been answered before and programmed by someone else unless it’s a real tough one.
In this case I searched “lua common divisors of two numbers” and found the function already written.
--[[ Functional Programming Example -- Greatest Common Divisor
H. Conrad Cunningham, Professor
Computer and Information Science
University of Mississippi
Developed for CSci 658, Software Language Engineering, Fall 2013
1234567890123456789012345678901234567890123456789012345678901234567890
2013-09-08: Completed prototype
This greatest common divisor (gcd) function is adapted from section
1.2.5 of Abelson and Sussman's Structure and Interpretation of
Computer Programs (SICP) textbook.
--]]
-- Function "gcd" computes the greatest common divisor of its two
-- nonegative number arguments using Euclid's algorithm. It is based
-- on property: If r is the remainder of a divided by b, then the
-- common divisors of a and b are precisely the same as the common
-- divisors of b and r.
-- Time complexity: O(log max(a,b))
-- Space complexity: O(1) with tail call optimization
local function gcd(a,b)
if type(a) == "number" and type(b) == "number" and
a == math.floor(a) and b == math.floor(b) then
if b == 0 then
return a
else
return gcd(b, a % b) -- tail recursion
end
else
error("Invalid argument to gcd (" .. tostring(a) .. "," ..
tostring(b) .. ")", 2)
end
end
https://john.cs.olemiss.edu/~hcc/csci658/notes/SICP_examples/Lua/gcd.lua
2 Likes
okay maybe i could forget to search before post.
2 Likes