Question
Write a collatz sequence in Lua I'm trying to write a collatz function in Lua (c(n)={3n+1,if n is odd; n/2 if n is even} )
Write a collatz sequence in Lua
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(" ")
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 pa2.collatz(k) while k > 1 do if k % 2 == 0 then k = k *0.5 else k = 3 * k + 1 end return k end end
There's an error when I use the code above( for i in collatz(3)...) ,it said "attempt to call a number value"
I need some help with this problem, thanks a lot!
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started