Jump to content

Module:Collatz sequence Generator

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by R1F4T (talk | contribs) at 09:37, 27 September 2024 (R1F4T moved page Module:Sandbox/R1F4T to Module:Collatz sequence Generator). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
--{{#invoke:collatz|collatz|<positive integer>}}

--this module generates the collatz sequence 


local p = {}

function p.collatz(frame)
    local n = tonumber(frame.args[1])  -- Get the input number
    if not n or n < 1 then
        return "Please provide a positive integer."
    end

    -- Get the bolding parameters (if "yes", bold even or odd numbers)
    local oddBold = frame.args['odd-bold'] == "yes"
    local evenBold = frame.args['even-bold'] == "yes"

    local sequence = {}

    -- Helper function to handle bolding
    local function maybe_bold(num)
        if num % 2 == 0 and evenBold then
            return "'''" .. num .. "'''"
        elseif num % 2 ~= 0 and oddBold then
            return "'''" .. num .. "'''"
        else
            return tostring(num)
        end
    end

    -- Add the first (starting) number to the sequence
    table.insert(sequence, maybe_bold(n))

    -- Loop through the Collatz sequence
    while n > 1 do
        if n % 2 == 0 then
            n = n / 2
        else
            n = 3 * n + 1
        end
        table.insert(sequence, "&#8594; " .. maybe_bold(n))  -- Add each new number with an arrow and conditional bolding
    end

    return table.concat(sequence, " ")  -- Return the formatted sequence
end

return p