Module:Collatz sequence Generator
Appearance
--{{#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 boldType = frame.args['bold'] -- Can be "odd", "even", or nil
local sequence = {}
-- Helper function to handle bolding
local function maybe_bold(num)
local result = tostring(num)
if num % 2 == 0 and boldType == "even" then
return "'''" .. result .. " (even)'''"
elseif num % 2 ~= 0 and boldType == "odd" then
return "'''" .. result .. " (odd)'''"
else
return result
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