Collatz Function Exploration

Define the Collatz function

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

Make sure it works:

col/@Range[10]

Iterate the function a number of times

n=17;(*starting value*)
numIter=20; (* how many times to iterate *)
seq={n}; (* list to store values in *)
Do[
n=col[n]; (* compute the next iterate *)
AppendTo[seq,n] (* stick the value on the end of the sequence*)
,numIter
]
(* print the sequence *)
seq

makeSeq[start_,numIter_]:=Module[{n=start, seq={n}},
Do[
n=col[n]; (* compute the next iterate *)
AppendTo[seq,n] (* stick the value on the end of the sequence*)
,numIter
];
(* return the sequence *)
seq
]

makeSeq[17,40]

makeSeq[27,200]

Collatz Conjecture: If we iterate the function col(n) enough times, the sequence always enters the cycle 4, 2, 1.

Write a module that computes the Collatz sequence (Collatz trajectory) until we find a 1.

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

computeTrajectory[27]

computeTrajectory[193]

computeTrajectory[47]

Here is another implementation involving an AND operator in the loop condition:

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

t27=computeTrajectory[27]

ListPlot[t27,AxesLabel->{"Iteration","Value"},Joined->True,Mesh->All,PlotRange->All]