(* ::Package:: *)

(************************************************************************)
(* This file was generated automatically by the Mathematica front end.  *)
(* It contains Initialization cells from a Notebook file, which         *)
(* typically will have the same name as this file except ending in      *)
(* ".nb" instead of ".m".                                               *)
(*                                                                      *)
(* This file is intended to be loaded into the Mathematica kernel using *)
(* the package loading commands Get or Needs.  Doing so is equivalent   *)
(* to using the Evaluate Initialization Cells menu command in the front *)
(* end.                                                                 *)
(*                                                                      *)
(* DO NOT EDIT THIS FILE.  This entire file is regenerated              *)
(* automatically each time the parent Notebook file is saved in the     *)
(* Mathematica front end.  Any changes you make to this file will be    *)
(* overwritten.                                                         *)
(************************************************************************)



(* :Name: PwM`Collatz` *)


(* :Book: Programming with Mathematica: An Introduction *)


(* :Author: Paul Wellin *)


(* :Summary: This package contains the functions defined in the solutions to the Collatz exercises in Chapter 13, Applications and packages. *)


(* :Context: PwM`Collatz` *)


(* :Package Version: 1.0 *)


(* :Copyright: Copyright 2012, Cambridge University Press *)


(* :History: Version 1.0 by Paul Wellin, Dec 2012 *)


(* :Keywords: Collatz sequence *)


(* :Source: Collatz.nb *)


(* :Mathematica Version: 8.0.4 *)


BeginPackage["PwM`Collatz`"]


CollatzSequence::usage="CollatzSequence[\!\(\*
StyleBox[\"n\", \"TI\"]\)] computes the sequence of Collatz iterates starting with initial value \!\(\*
StyleBox[\"n\", \"TI\"]\). The sequence terminates as soon as it reaches the value 1.";


CollatzSequence::notint="First argument, `1`, to CollatzSequence must be a positive integer.";


Begin["`Private`"]


collatz[n_?EvenQ]:=n/2


collatz[n_?OddQ]:=3n+1


CollatzSequence[n_]:=
If[IntegerQ[n]&&n>=0,
NestWhileList[collatz,n,#!=1&],
Message[CollatzSequence::notint,n]
]


CollatzSequence[_,args__]/;Message[CollatzSequence::argx,CollatzSequence,Length[{args}]+1]:=Null


End[]


EndPackage[]



