home *** CD-ROM | disk | FTP | other *** search
/ Liren Large Software Subsidy 9 / 09.iso / e / e032 / 3.ddi / FILES / PROGRAMM.PAK / COLLATZ.M < prev    next >
Encoding:
Text File  |  1992-07-29  |  1.9 KB  |  68 lines

  1.  
  2. (*********************************************************************
  3.  
  4.     Copyright 1991 by Roman E. Maeder
  5.     
  6.     Adapted from
  7.     Roman E. Maeder: Programming in Mathematica,
  8.     Second Edition, Addison-Wesley, 1991.
  9.  
  10.     Permission is hereby granted to make copies of this file for
  11.     any purpose other than direct profit, or as part of a
  12.     commercial product, provided this copyright notice is left
  13.     intact.  Sale, other than for the cost of media, is prohibited.
  14.     
  15.     Permission is hereby granted to reproduce part or all of
  16.     this file, provided that the source is acknowledged.
  17.  
  18.  *********************************************************************)
  19.  
  20.     (* Enclosed with Mathematica by permission *)
  21.  
  22.  
  23. BeginPackage["Examples`Collatz`"]
  24.  
  25. Collatz::usage =
  26.     "Collatz[n] gives a list of the iterates in the 3n+1 problem,
  27.     starting from n. The conjecture is that this sequence always
  28.     terminates."
  29.  
  30. StoppingTime::usage = "StoppingTime[n] finds the total stopping time
  31.     of the integer n. This is the length of the Collatz sequence
  32.     before hitting 1."
  33.  
  34. FindMaxima::usage = "FindMaxima[from] reports successive maxima of the
  35.     total stopping time starting the search with the integer from."
  36.  
  37. Begin["`Private`"]
  38.  
  39. Collatz[n_Integer] := AppendCollatz[{}, n]
  40.  
  41. AppendCollatz[sofar_, 1] := Flatten[{sofar, 1}]
  42.  
  43. AppendCollatz[sofar_, n_Integer] :=
  44.     AppendCollatz[{sofar, n}, 3 n + 1]    /; OddQ[n]
  45.  
  46. AppendCollatz[sofar_, n_Integer] :=
  47.     AppendCollatz[{sofar, n}, n / 2]    /; EvenQ[n] && n != 0
  48.  
  49. StoppingTime[n_Integer?Positive] :=
  50.     Module[{i=1, m=n}, While[m != 1, m = If[OddQ[m], 3m+1, m/2]; i++];i ]
  51.  
  52. FindMaxima[low_] :=
  53.     Module[{m=0, n=0, i=low, j},
  54.         While[ True,
  55.             j = StoppingTime[i];
  56.             If[j > m, m = j; n = i;
  57.                       Print["StoppingTime[", n, "] = ", m] ];
  58.             i++;
  59.             If[ Mod[i, 100] == 0, Print["i = ", i] ]
  60.         ]
  61.     ]
  62.  
  63. End[]
  64.  
  65. Protect[ Collatz, StoppingTime, FindMaxima ]
  66.  
  67. EndPackage[]
  68.