Module:Collatz sequence Generator
Appearance
--{{#invoke:Sandbox/R1F4T|collatz|10}}
--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 bold settings from parameters
local odd_bold = frame.args["odd-bold"] == "yes"
local even_bold = frame.args["even-bold"] == "yes"
local sequence = {}
-- Helper function to format each number based on its parity
local function format_number(num)
if num % 2 == 0 and even_bold then
return "'''"..num.."'''"
elseif num % 2 ~= 0 and odd_bold then
return "'''"..num.."'''"
else
return tostring(num)
end
end
-- Add the first number, bold if necessary
table.insert(sequence, format_number(n))
-- Generate the rest of the sequence
while n > 1 do
if n % 2 == 0 then
n = n / 2
else
n = 3 * n + 1
end
table.insert(sequence, "→ " .. format_number(n)) -- Add arrow and formatted number
end
return table.concat(sequence, " ") -- Return the formatted sequence
end
return p