Message Boards Message Boards

0
|
5706 Views
|
6 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Printing outputs for Collatz conjecture?

Posted 3 years ago

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.

Collatz

Thank you.

Attachments:
POSTED BY: Jonathan Bell
6 Replies
Posted 3 years ago

Hi Jonathan,

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

POSTED BY: Rohit Namjoshi
Posted 3 years ago

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

POSTED BY: Jonathan Bell
Posted 3 years ago

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

POSTED BY: Hans Milton
Posted 3 years ago

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

POSTED BY: Jonathan Bell
Posted 3 years ago

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

POSTED BY: Jonathan Bell

You might want to look at https://mathworld.wolfram.com/CollatzProblem.html 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.

POSTED BY: Moderation Team
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract