Wolfram Research

Function Repository Resource:

Collatz

Source Notebook

Get the Collatz sequence starting with a given value

Contributed by: Enrique Zeleny

ResourceFunction["Collatz"][n]

gives the Collatz sequence starting with n.

ResourceFunction["Collatz"][n,m]

gives the first m iterations.

Details and Options

The Collatz sequence is obtained by starting from a positive integer and applying repeatedly the following operations: If the number is even, divide it by two, and If the number is odd, triple it and add one.
The Collatz conjecture states that this sequence always terminates in 1.

Examples

Basic Examples

Collatz sequence for 13:

In[1]:=
ResourceFunction["Collatz"][13]
Out[1]=

Show just the first 30 iterates for 27:

In[2]:=
ResourceFunction["Collatz"][27, 30]
Out[2]=

Highlight odd values:

In[3]:=
If[OddQ[#], Style[#, 18], #] & /@ ResourceFunction["Collatz"][27]
Out[3]=

Plot all the iterates for 27:

In[4]:=
ListLinePlot[ResourceFunction["Collatz"][27]]
Out[4]=

Plot the number of iterates needed for the first 100 integers:

In[5]:=
DiscretePlot[Length@ResourceFunction["Collatz"][n], {n, 100}]
Out[5]=

Number of iterates needed for the first 2000 integers:

In[6]:=
ListPlot[Table[{n, Length@ResourceFunction["Collatz"][n]}, {n, 2000}]]
Out[6]=

Graph of the iterates for the first 26 integers:

In[7]:=
GraphPlot[
 Union[Flatten[
   Table[Apply[Rule, Partition[ResourceFunction["Collatz"][n], 2, 1], {1}], {n, 3, 26}]]], VertexLabeling -> True, VertexRenderingFunction -> (Inset[#2, #1] &)]
Out[7]=

Graph of the iterates for 500:

In[8]:=
Graph[Union[
  Flatten[Table[
    Apply[Rule, Partition[ResourceFunction["Collatz"][n], 2, 1], {1}], {n, 3, 500}]]]]
Out[8]=

Paths of the iterates for the first 100 integers:

In[9]:=
ListPlot[Table[{n, #} & /@ ResourceFunction["Collatz"][n], {n, 100}], PlotRange -> {{0, 100}, {0, 200}}]
Out[9]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information