Printing outputs for Collatz conjecture?

Hi, all. I just found this Collatz conjecture:
Choose a number. If the number is even, divide it by two and repeat the process.
If the number is odd, multiply the number by three and add 1. Then divide the number by two.

It is conjectured this leads to an infinite loop with the last three numbers in the list of outputs being 4, 2, 1.
I’m trying to make a loop that prints the outputs and stops I after the three terms 4, 2, 1 are printed in order.

I think I need to include pattern matching code to stop the loop after 4, 2, 1 are printed in order.

Thank you.

Collatz NB.nb (5.92 KB)

You might want to look at

and some of the videos on Collatz on YouTube. Collatz has been checked to over 10^18, so your
program will run basically forever. There are also many Collatz calculators on the internet to give you more guidance on what is possible and interesting.

Thanks for the response. The Collatz conjecture is interesting, but I’m just trying to create code to explore the conjecture.

You could use NestWhileList

n=17;    
NestWhileList[If[EvenQ[#],#/2,3*#+1]&,n,(Print[{##}];{##}!={4,2,1})&,3]

This code is just an adaption of examples in the documentation

Thank you, Hans.

I appreciate the help. There are many ways to accomplish the same task in Mathematica which is great, but can also be a bit overwhelming. I have a lot to learn.

Be safe out there.

JWB

Hi Jonathan,

Take a look at this and subsequent answers for efficient code. For a nice visualization see this.

Thank you, Rohit.

I first heard of this problem a couple of days ago. It’s easy to understand, but I need to learn more about writing loops in Mathematica.

Be safe out there.

JWB