% Generate the hailstone sequence for a number hailstone = iter (n: int) yields (int) while true do yield(n) if n=1 then break end if n//2 = 0 then n := n/2 else n := 3*n + 1 end end end hailstone % Make an array from an iterator iter_array = proc [T,U: type] (i: itertype (U) yields (T), s: U) returns (array[T]) arr: array[T] := array[T]$[] for item: T in i(s) do array[T]$addh(arr, item) end return(arr) end iter_array start_up = proc () po: stream := stream$primary_output() % Generate the hailstone sequence for 27 h27: array[int] := iter_array[int,int](hailstone, 27) lo27: int := array[int]$low(h27) hi27: int := array[int]$high(h27) stream$putl(po, "The hailstone sequence for 27 has " || int$unparse(array[int]$size(h27)) || " elements.") stream$puts(po, "The first 4 elements are:") for i: int in int$from_to(lo27, lo27+3) do stream$puts(po, " " || int$unparse(h27[i])) end stream$puts(po, ", and the last 4 elements are:") for i: int in int$from_to(hi27-3, hi27) do stream$puts(po, " " || int$unparse(h27[i])) end stream$putl(po, "") % Find whichever sequence < 100 000 has the longest sequence maxnum: int := 0 maxlen: int := 0 for i: int in int$from_to(1, 99999) do len: int := array[int]$size(iter_array[int,int](hailstone, i)) if len > maxlen then maxnum, maxlen := i, len end end stream$putl(po, int$unparse(maxnum) || " has the longest hailstone sequence < 100000: " || int$unparse(maxlen)) end start_up