Module:Collatz sequence Generator
Appearance
local p = {}
function p.collatz(frame)
local n = tonumber(frame.args[1]) -- Input number
if not n or n < 1 then
return "Please provide a positive integer."
end
local bold = frame.args['bold'] -- Bold parameter
local max = tonumber(frame.args['max']) -- Maximum steps
local display_steps = frame.args['steps'] == "yes" -- Whether to display total steps
local hide_sequence = frame.args['hide'] == "yes" -- Whether to hide the sequence
-- Check if both 'hide' and 'max' are set (conflict)
if hide_sequence and max then
return "Error: Sequence is hidden. Please remove the 'max' parameter."
end
local sequence, count = {}, 0 -- Initialize sequence and counter
-- Helper to conditionally bold numbers
local function maybe_bold(num)
local result = tostring(num)
if (num % 2 == 0 and bold == "even") or (num % 2 ~= 0 and bold == "odd") then
return "'''" .. result .. "'''" -- Bold even or odd numbers
end
return result -- Return unbolded if condition not met
end
-- Function to handle the Collatz logic and format sequence
local function collatz_step(num)
table.insert(sequence, maybe_bold(num))
count = count + 1 -- Increment step count
return num % 2 == 0 and num / 2 or 3 * num + 1 -- Next Collatz step
end
-- Main Collatz loop
while n > 1 do
if max and count >= max then -- Stop if max steps reached
table.insert(sequence, "..." .. tostring(math.floor(math.log(n, 2)) + 1) .. " more") -- Estimate remaining steps
break
end
n = collatz_step(n) -- Perform Collatz step
end
collatz_step(n) -- Final step to 1
-- Handle 'hide' option
if hide_sequence then
return display_steps and (count - 1) or "(sequence is hidden)"
end
-- Return formatted sequence
local result = table.concat(sequence, ", ")
if display_steps then
result = result .. " (Total steps: " .. (count - 1) .. ")"
end
return result
end
return p