3
$\begingroup$

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.

$\endgroup$
  • 2
    $\begingroup$ s1 might not be in the collatz path of x1... $\endgroup$ – Sjoerd C. de Vries Sep 7 '14 at 8:44
  • $\begingroup$ Why? @SjoerdC.deVries $\endgroup$ – Arturo Ortiz Sep 9 '14 at 0:54
  • $\begingroup$ 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. $\endgroup$ – Sjoerd C. de Vries Sep 9 '14 at 5:46
2
$\begingroup$
collatz = Switch[Mod[#, 2], 0, #/2, 1, 3 # + 1] &;
count[x1_, s1_] := Length@NestWhileList[collatz, x1, # != s1 &]
count[100, 1]

(* 26 *)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks @belisarius I think this is a good option for my code. $\endgroup$ – Arturo Ortiz Sep 7 '14 at 5:47
1
$\begingroup$

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

| improve this answer | |
$\endgroup$
  • $\begingroup$ Thanks @Tangshutao, I appreciate your answer!! What's the difference between NestWhileList and FixedPointList? $\endgroup$ – Arturo Ortiz Sep 9 '14 at 0:47
  • 1
    $\begingroup$ @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. $\endgroup$ – xyz Sep 9 '14 at 2:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.