(* ::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: EPM`Collatz` *)


(* :Book: Essentials of programming in Mathematica *)


(* :Author: Paul Wellin *)


(* :Summary: This package contains the functions defined in the solutions to the Collatz exercises in Chapter 10 Packages. *)


(* :Context: EPM`Collatz` *)


(* :Package Version: 1.0 *)


(* :Copyright: Copyright 2015, Paul R Wellin *)


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


(* :Keywords: Collatz sequence, PositiveIntegerQ *)


(* :Source: Collatz.nb *)


(* :Mathematica Version: 10.3 *)


(* Tested in Mathematica 11.1 *)


Remove[CollatzSequence];


BeginPackage["EPM`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="The argument, `1`, to CollatzSequence must be a positive integer.";


Begin["`Private`"]


collatz[n_?EvenQ]:=n/2


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


positiveIntegerQ[n_]:=IntegerQ[n]&&Positive[n]


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


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


End[]


EndPackage[]



