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 10:11, 27 September 2024. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
--{{#invoke:Collatz sequence Generator|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 parameter
    local bold = frame.args['bold'] 

    local sequence = {}

    -- Helper function to handle bolding
    local function maybe_bold(num)
        local result = tostring(num)
        if num % 2 == 0 and bold == "even" then  -- Check if the number is even
            return "'''" .. result .. "'''"  -- Bold if 'even'
        elseif num % 2 ~= 0 and bold == "odd" then  -- Check if the number is odd
            return "'''" .. result .. "'''"  -- Bold if 'odd'
        else
            return result  -- Return as is if not bolded
        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, maybe_bold(n))  -- Add each new number with conditional bolding
    end

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

return p