Calculate largest possible number that is a multiple of every number in a table

I want to micro-milli-nano-optimize a simple function but screw it up because any optimization I attempt inevitably always leads to the script being slower than before, but keep it anyway because I wasted my time on it and I don’t want to undo it.

For this I need to I find the largest number that is a multiple of each number in a table.
Let’s say I have this set of numbers:
20, 35, 50, 65, 75
In this case the largest number that is a multiple of every one of those in the example above is 5. How can I find this for any arbitrary set of numbers?

quick pls answer before the dox mandates kick in and i get locked out of this forum

Does this script work for you?

local function gcd(a, b)
    while b ~= 0 do
        a, b = b, a % b
    end
    return a
end

local function gcdList(numbers)
    local result = numbers[1]
    for i = 2, #numbers do
        result = gcd(result, numbers[i])
    end
    return result
end

local nums = {20, 35, 50, 65, 75}
print(gcdList(nums))

Yeah it looks like it’s giving the correct results, can you explain the code a bit more in detail? Namely what’s going on in the gcd() function?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.