Collatz Tree

Ian Ford, WRI
​
Thu 18 Jan 2024
Expandable (lazy) and collapsible trees are on the roadmap. In the meantime...
◼
  • Define the iterator for the Collatz conjecture:
  • In[]:=
    collatz[n_?EvenQ]:=n/2​​collatz[n_?OddQ]:=(3n+1)/2
    ◼
  • Compute the orbit of an integer:
  • In[]:=
    collatzList[n_]:=NestWhileList[collatz,n,Not@*EqualTo[1]]
    In[]:=
    collatzList[25]
    Out[]=
    {25,38,19,29,44,22,11,17,26,13,20,10,5,8,4,2,1}
    ◼
  • Compute a graph of orbits:
  • In[]:=
    collatzTreeGraph[n_]:=EdgeDelete[ResourceFunction["NestWhileGraph"][collatz,Range[n],Not@*ConnectedGraphQ@*UndirectedGraph,VertexLabels->Automatic],12]//LayeredGraph
    In[]:=
    collatzTreeGraph[25]
    Out[]=
    ◼
  • For the reverse, first define the iterator that produces the branches:
  • In[]:=
    anticollatz[n_]:=With[{m=(2n-1)/3},If[IntegerQ[m]&&m!=1,{2n,m},{2n}]]
    ◼
  • Compute the tree down to a certain level:
  • In[]:=
    collatzTree[level_]:=NestTree[anticollatz,1,level]
    In[]:=
    collatzTree[10]
    Out[]=
    ◼
  • Get an outline of the tree that can be interactively opened and closed:
  • In[]:=
    TreeOutline[%]
    Out[]=
    1
    ​
    2
    ​
    4
    ​
    8
    ​
    16
    ​
    32
    ​
    64
    21
    5
    ​
    10
    ​
    20
    ​
    40
    ​
    80
    ​
    160
    53
    ​
    106
    35
    13
    ​
    26
    ​
    52
    17
    ​
    34
    11
    3
    ​
    6
    ​
    12
    ​
    24
    ◼
  • I submitted an interactive version of NestTree to the Wolfram Function Repository that allows branches to be expanded by clicking on the leaves:
  • In[]:=
    ResourceFunction["NestTreeInteractive"][anticollatz,1]
    Out[]=
    ◼
  • As implemented, the branches can’t be collapsed. The output is also reset when the notebook is closed, so to save the output, select the cell and choose the Cell ▶ Convert To ▶ Bitmap menu item. Hope this helps!