
(*********************************************************************

	Copyright 1991 by Roman E. Maeder
	
	Adapted from
	Roman E. Maeder: Programming in Mathematica,
	Second Edition, Addison-Wesley, 1991.

	Permission is hereby granted to make copies of this file for
	any purpose other than direct profit, or as part of a
	commercial product, provided this copyright notice is left
	intact.  Sale, other than for the cost of media, is prohibited.
	
	Permission is hereby granted to reproduce part or all of
	this file, provided that the source is acknowledged.

 *********************************************************************)

	(* Enclosed with Mathematica by permission *)


BeginPackage["Examples`Collatz`"]

Collatz::usage =
	"Collatz[n] gives a list of the iterates in the 3n+1 problem,
	starting from n. The conjecture is that this sequence always
	terminates."

StoppingTime::usage = "StoppingTime[n] finds the total stopping time
	of the integer n. This is the length of the Collatz sequence
	before hitting 1."

FindMaxima::usage = "FindMaxima[from] reports successive maxima of the
	total stopping time starting the search with the integer from."

Begin["`Private`"]

Collatz[n_Integer] := AppendCollatz[{}, n]

AppendCollatz[sofar_, 1] := Flatten[{sofar, 1}]

AppendCollatz[sofar_, n_Integer] :=
	AppendCollatz[{sofar, n}, 3 n + 1]	/; OddQ[n]

AppendCollatz[sofar_, n_Integer] :=
	AppendCollatz[{sofar, n}, n / 2]	/; EvenQ[n] && n != 0

StoppingTime[n_Integer?Positive] :=
	Module[{i=1, m=n}, While[m != 1, m = If[OddQ[m], 3m+1, m/2]; i++];i ]

FindMaxima[low_] :=
	Module[{m=0, n=0, i=low, j},
		While[ True,
			j = StoppingTime[i];
			If[j > m, m = j; n = i;
			          Print["StoppingTime[", n, "] = ", m] ];
			i++;
			If[ Mod[i, 100] == 0, Print["i = ", i] ]
		]
	]

End[]

Protect[ Collatz, StoppingTime, FindMaxima ]

EndPackage[]
