Apply Collatz Funtion to solve and print the answer

Good day to all!

The objective of my task is apply the collatz function for a number x1 and print the exact number of iterations until s1. I want to create a function using Module:

CollatzFunction[x1_, s1_]:= Module[{.......};


Print iterations to s1-> "number of iterations"

I barely have an idea using Nest[], but I don't know how to apply Nest until the s1 number is reached.

Please, help in this task, it's just a step towards creating a more complicated function. Thanks.

• s1 might not be in the collatz path of x1... Sep 7, 2014 at 8:44
• Why? @SjoerdC.deVries Sep 9, 2014 at 0:54
• Because the collatz procedure generates a tree and if you start in one branch you will miss numbers in other branches or which are higher up in your own branch. Sep 9, 2014 at 5:46

collatz = Switch[Mod[#, 2], 0, #/2, 1, 3 # + 1] &;
count[x1_, s1_] := Length@NestWhileList[collatz, x1, # != s1 &]
count[100, 1]

(* 26 *)

• Thanks @belisarius I think this is a good option for my code. Sep 7, 2014 at 5:47

My solution:

the definition of Collatz

Collatz[n_Integer?OddQ] := 3 n + 1
Collatz[n_Integer?EvenQ] := n/2


the definition of CollatzSeqLength

CollatzSeqLength[num_Integer,s1_Integer] :=
Length@NestWhileList[Collatz, num, # != s1 &]


Applying1:

CollatzSeqLength[100, 1]


26

Or

 CollatzSeqLength2[num_Integer,s1_Integer] :=
Length@Most@FixedPointList[If[# != s1, Collatz@#, s1] &, num]


Applying2:

CollatzSeqLength2[100, 1]


26

• Thanks @Tangshutao, I appreciate your answer!! What's the difference between NestWhileList and FixedPointList? Sep 9, 2014 at 0:47
• @MMSci Arturo Ortiz The Mathematica documentation has stated clearly. NestWhileList[f,expr,test] (reference.wolfram.com/language/ref/NestWhileList.html) generates a list of the results of applying f repeatedly, starting with expr, and continuing until applying test to the result no longer yields True. FixedPointList[f,expr] (reference.wolfram.com/language/ref/…) generates a list giving the results of applying f repeatedly, starting with expr, until the results no longer change.
– xyz
Sep 9, 2014 at 2:25