Generating a Collatz tree

I have written a short Mathematica program that generates the function tree of the Collatz function.  The code is in the document collatz.nb on the abmath website.

Examples

Here are some examples.  The first one is generated by the integers between 1 and 26.  (27 is to be avoided because it makes a shoot that is 111 nodes high.)  The primes from 1 to 26 generates the same tree. 

This one is generated by the odd numbers from 1 to 26: 

This is generated by the even numbers from 1 to 50:

 

Remark

This program is not of great import, but it was fun doing it and I learned more Mathematica. In particular, I learned that you cannot assign to a parameter in a function definition. For example, I had to write fv[gl_List, n_Integer] := (nn := n; ggl := {nn}; (Sow[1]; While[! MemberQ[ggl, cf[nn]], (Sow[nn]; Sow[cf[nn]]); nn = cf[nn]]) // Reap) instead of fv[gl_List, n_Integer] := (Sow[1]; While[! MemberQ[gl, cf[n]], (Sow[n]; Sow[cf[n]]); n = cf[n]]) // Reap) (where n:=cf[n] wouldn't have worked either).

Send to Kindle

Leave a Reply

Your email address will not be published. Required fields are marked *