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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!