Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Finance The Role Of Data Analytics In Manda Due Diligence

Authors: Ps Publishing

1st Edition

B0CR6SKTQG, 979-8873324675

More Books

Students also viewed these Databases questions

Question

How does selection differ from recruitment ?

Answered: 1 week ago