Question: This is a Lua programming problem I'm trying to write a collatz function in Lua (c(n)={3n+1,if n is odd; n/2 if n is even} )
This is a Lua programming problem I'm trying to write a collatz function in Lua (c(n)={3n+1,if n is odd; n/2 if n is even} ) start at a positive integer n
For example the Collatz sequence starting at 3 is
3,10,5,16,8,4,2,1.
And it must be able to execute by this code:
for i in collatz(3) do io.write(i.." ") end io.write(" ") (Because we are writing a module, and this code is given by the instructor, so it has to be this way to call the function) then it should produce the following output: 3 10 5 16 8 4 2 1 If collatz(3) is replaced by collatz(1), then the output will be the following: 1
Here's the function I have now: function collatz(k) return function() if k > 1 then if k % 2 == 0 then k = k *0.5 else k = 3 * k + 1 end return k end end end
The problem I have is how to include the starting number, and how to return 1 for collatz(1) instead of an empty string I need some help with this problem, thanks a lot!
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
