Hailstone sequence: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Not a robot (talk | contribs) (Add CLU) |
||
Line 2,585: | Line 2,585: | ||
{:num i, :len (count (hailstone-seq i))}))] |
{:num i, :len (count (hailstone-seq i))}))] |
||
(println "Maximum length" max-len "was found for hailstone(" max-i ")."))</lang> |
(println "Maximum length" max-len "was found for hailstone(" max-i ")."))</lang> |
||
=={{header|CLU}}== |
|||
<lang clu>% 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</lang> |
|||
{{out}} |
|||
<pre>The hailstone sequence for 27 has 112 elements. |
|||
The first 4 elements are: 27 82 41 124, and the last 4 elements are: 8 4 2 1 |
|||
77031 has the longest hailstone sequence < 100000: 351</pre> |
|||
=={{header|COBOL}}== |
=={{header|COBOL}}== |