Collatz Exploration

Define the Collatz Function

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

Make sure it works:

col/@Range[10]

Iterate the Collatz function

n=11; (* starting value *)
numIter=20; (* number of times to iterate *)
values={n}; (* keep track of the values *)
Do[
n=col[n];  (* compute the next values *)
AppendTo[values,n] (* stick the value on to the sequence *)
,numIter
]
(* display the sequence *)
values

Make a module:

computeSequence[start_,numIter_]:=Module[{n=start,values={start}},
Do[
n=col[n];  (* compute the next values *)
AppendTo[values,n] (* stick the value on to the sequence *)
,numIter
];
(* return the sequence *)
values
]

computeSequence[11,20]

computeSequence[108,200]

s27=computeSequence[27,125]

s129=computeSequence[129,125]

Conjecture: For any starting value n, the sequence of Collatz iterates eventually reaches 4, 2, 1.

Code to compute Collatz sequence until we find a 1

Collatz trajectory: sequence of Collatz iterates from n to 1.

computeTrajectory[start_]:=Module[{traj={start},n=start,maxIter=100000},
(* compute the trajectory until we find 1 *)
While[n!=1,
n=col[n];
AppendTo[traj,n];
If[Length[traj]==maxIter,Break[] ]
];
(* return the trajectory *)
traj
]

Try it out:

computeTrajectory[27]

computeTrajectory[3711]

another implementation:

computeTrajectory[start_]:=Module[{traj={start},n=start,maxIter=100000},
(* compute the trajectory until we find 1 *)
While[n!=1&&Length[traj]<maxIter,
n=col[n];
AppendTo[traj,n]
];
(* return the trajectory *)
traj
]

computeTrajectory[2435251]

Plot a Collatz Trajectory

t27=computeTrajectory[27]

ListPlot[t27,AxesLabel->{"iterations","value"},PlotRange->All,Joined->True,Mesh->All,PlotStyle->Orange,MeshStyle->{Blue,PointSize[Large]}]

ListPlot[computeTrajectory[93],
AxesLabel->{"iterations","value"},PlotRange->All,Joined->True,Mesh->All,PlotStyle->Orange,MeshStyle->{Blue,PointSize[Large]}]

Another option for defining the Collatz function:

c[n_]:=If[Mod[n,2]==1,3n+1,n/2]

c/@Range[10]