The Collatz Function

Math 242 Modern Computational Mathematics

Define the Collatz function

The Collatz function Col(n) is defined for any positive integer n as follows: if n is even, then Col(n)=(n/2), but if n is odd, then Col(n)=3n+1.

col[n_?OddQ]:=3n+1
col[n_?EvenQ]:=n/2

col/@Range[10]

Iterate a fixed number of times

Let's write some code to iterate the Collatz function from some starting integer n.

n=11; (* starting value *)
maxIter=20; (* number of times to iterate *)
seq={n}; (* sequece to hold the values *)
Do[
n=col[n];
AppendTo[seq,n],
maxIter
]
seq

We can put our code in a module to make it easy to run for different starting values:

makeSeq[start_,numIter_]:=Module[
{n=start,seq={start}},
Do[
n=col[n];
AppendTo[seq,n],
numIter
];
seq
]

Test my module:

makeSeq[11,30]

makeSeq[32,20]

makeSeq[71,20]

makeSeq[73,200]

Collatz Conjecture

Conjecture: For any starting positive integer n, the Collatz sequence starting with n eventually reaches 1.

Iterate until we find a 1

Collatz Trajectory: the sequence of Collatz iterates starting with n until we reach a 1

computeTrajectory[start_,maxIter_]:=Module[
{n=start,seq={start},count=0}, 
(* repeat until we get 1 *)
While[n!=1,
n=col[n];
AppendTo[seq,n];
count+=1;
If[count==maxIter,Break[]]
];
(*Print[count];*)
seq (* return the sequence *)
]

Try it out:

computeTrajectory[73,1000]

traj=computeTrajectory[27,1000]

Plotting Collatz Trajectories

ListPlot[traj,Joined->True,PlotRange->All,AxesLabel->{"iteration","value"},PlotStyle->Orange,Mesh->All,MeshStyle->{Blue,PointSize[Medium]}]

We could even put the plot function in a Module, like this:

plotTrajectory[traj_]:=ListPlot[traj,PlotRange->All,AxesLabel->{"iteration","value"},Joined->True,PlotStyle->Orange,Mesh->All,MeshStyle->{Blue,PointSize[Medium]}]

traj=computeTrajectory[54,1000];
plotTrajectory[traj]