Hailstone sequence: Difference between revisions

add ABC
(add ABC)
 
(139 intermediate revisions by 56 users not shown)
Line 10:
 
 
This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):
The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the ''Collatz sequence''.
:::*   hailstone sequence,   hailstone numbers
:::*   3x + 2 mapping,   3n + 1 problem
:::*   Collatz sequence
:::*   Hasse's algorithm
:::*   Kakutani's problem
:::*   Syracuse algorithm,   Syracuse problem
:::*   Thwaites conjecture
:::*   Ulam's problem
 
 
The hailstone sequence is also known as   ''hailstone numbers''   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).
 
 
Line 21 ⟶ 32:
;See also:
*   [http://xkcd.com/710 xkcd] (humourous).
*   [https://terrytao.files.wordpress.com/2020/02/collatz.pdf The Notorious Collatz conjecture] Terence Tao, UCLA (Presentation, pdf).
*   [https://www.youtube.com/watch?v=094y1Z2wpJg The Simplest Math Problem No One Can Solve] Veritasium (video, sponsored).
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F hailstone(=n)
V seq = [n]
L n > 1
n = I n % 2 != 0 {3 * n + 1} E n I/ 2
seq.append(n)
R seq
 
V h = hailstone(27)
assert(h.len == 112 & h[0.<4] == [27, 82, 41, 124] & h[(len)-4 ..] == [8, 4, 2, 1])
 
V m = max((1..99999).map(i -> (hailstone(i).len, i)))
print(‘Maximum length #. was found for hailstone(#.) for numbers <100,000’.format(m[0], m[1]))</syntaxhighlight>
 
{{out}}
<pre>
Maximum length 351 was found for hailstone(77031) for numbers <100,000
</pre>
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Hailstone sequence 16/08/2015
HAILSTON CSECT
USING HAILSTON,R12
Line 126 ⟶ 160:
XDEC DS CL12
YREGS
END HAILSTON</langsyntaxhighlight>
{{out}}
<pre>
Line 134 ⟶ 168:
 
=={{header|ABAP}}==
<syntaxhighlight lang="abap">
<lang ABAP>
CLASS lcl_hailstone DEFINITION.
PUBLIC SECTION.
Line 224 ⟶ 258:
cl_demo_output=>write( lcl_hailstone=>get_longest_sequence_upto( 100000 ) ).
cl_demo_output=>display( ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 241 ⟶ 275:
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO RETURN hailstone n:
PUT {} IN seq
WHILE 1=1:
PUT n IN seq[#seq]
SELECT:
n=1: RETURN seq
n mod 2=0: PUT floor(n/2) IN n
n mod 2=1: PUT 3*n+1 IN n
RETURN seq
 
PUT hailstone 27 IN h27
WRITE "Length of Hailstone sequence for 27:", #h27/
WRITE "First 4 elements:", h27[0], h27[1], h27[2], h27[3]/
WRITE "Last 4 elements:", h27[#h27-4], h27[#h27-3], h27[#h27-2], h27[#h27-1]/
 
PUT 0, 0 IN longest, length
FOR n IN {1..100000}:
PUT hailstone n IN hn
IF #hn > length:
PUT n, #hn IN longest, length
 
WRITE longest, "has the longest hailstone sequence < 100,000, of length:", length/</syntaxhighlight>
{{out}}
<pre>Length of Hailstone sequence for 27: 112
First 4 elements: 27 82 41 124
Last 4 elements: 8 4 2 1
77031 has the longest hailstone sequence < 100,000, of length: 351</pre>
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun hailstone (len)
(loop for x = len
then (if (evenp x)
Line 257 ⟶ 319:
(if (> new-mx mx)
(max-hailstone-start (1- limit) new-mx limit)
(max-hailstone-start (1- limit) mx curr)))))</langsyntaxhighlight>
 
{{out}}
Line 271 ⟶ 333:
=={{header|Ada}}==
Similar to [[#C|C method]]:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure hailstone is
type int_arr is array(Positive range <>) of Integer;
Line 309 ⟶ 371:
end loop;
put_line(Integer'Image(nmax)&" max @ n= "&Integer'Image(stonemax));
end hailstone;</langsyntaxhighlight>
{{out}}
<pre>
Line 321 ⟶ 383:
 
hailstones.ads:
<langsyntaxhighlight Adalang="ada">package Hailstones is
type Integer_Sequence is array(Positive range <>) of Integer;
function Create_Sequence (N : Positive) return Integer_Sequence;
end Hailstones;</langsyntaxhighlight>
hailstones.adb:
<langsyntaxhighlight Adalang="ada">package body Hailstones is
function Create_Sequence (N : Positive) return Integer_Sequence is
begin
Line 340 ⟶ 402:
end if;
end Create_Sequence;
end Hailstones;</langsyntaxhighlight>
example main.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Hailstones;
 
Line 384 ⟶ 446:
Ada.Text_IO.Put_Line ("with N =" & Integer'Image (Longest_N));
end;
end Main;</langsyntaxhighlight>
{{out}}
<pre>Length of 27: 112
Line 393 ⟶ 455:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
print_hailstone(integer h)
{
Line 400 ⟶ 462:
while (h ^ 1) {
lb_p_integer(l, h);
h = __hold(h & 1, ? 3 * h + 1, : h / 2);
}
 
o_form("hailstone sequence for ~ is ~1 ~ ~ ~ .. ~ ~ ~ ~, it is ~ long\n",
l[0], l[1], l[2], l[3], l[-3], l[-2], l[-1], 1, l_length(~l) + 1);
}
 
Line 411 ⟶ 473:
{
integer e, i, m;
recordindex r;
 
m = 0;
Line 421 ⟶ 483:
l = 1;
while (h ^ 1) {
if (r_j_integeri_j_integer(k, r, itoa(h))) {
l += k;
break;
} else {
l += 1;
h = __hold(h & 1, ? 3 * h + 1, : h / 2);
}
}
 
r_f_integer(r, itoa([i),] = l - 1);
 
if (m < l) {
Line 440 ⟶ 502:
}
 
o_form("hailstone sequence length for ~ is ~ long\n", e, m);
}
 
Line 450 ⟶ 512:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>hailstone sequence for 27 is 27 82 41 124 .. 8 4 2 1, it is 112 long
hailstone sequence length for 77031 is 351 long</pre>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<syntaxhighlight lang="algol60">begin
comment Hailstone sequence - Algol 60;
integer array collatz[1:400]; integer icollatz;
integer procedure mod(i,j); value i,j; integer i,j;
mod:=i-(i div j)*j;
integer procedure hailstone(num);
value num; integer num;
begin
integer i,n;
icollatz:=1; n:=num; i:=0;
collatz[icollatz]:=n;
for i:=i+1 while n notequal 1 do begin
if mod(n,2)=0 then n:=n div 2
else n:=(3*n)+1;
icollatz:=icollatz+1;
collatz[icollatz]:=n
end;
hailstone:=icollatz
end hailstone;
integer i,nn,ncollatz,count,nlongest,nel,nelcur,nnn;
nn:=27;
ncollatz:=hailstone(nn);
outstring(1,"sequence for"); outinteger(1,nn); outstring(1," :\n");
for i:=1 step 1 until ncollatz do outinteger(1,collatz[i]);
outstring(1,"\n");
outstring(1,"number of elements:"); outinteger(1,ncollatz);
outstring(1,"\n\n");
nlongest:=0; nel:=0; nnn:=100000;
for count:=1, count+1 while count<nnn do begin
nelcur:=hailstone(count);
if nelcur>nel then begin
nel:=nelcur;
nlongest:=count
end
end;
outstring(1,"number <"); outinteger(1,nnn);
outstring(1,"with the longest sequence:"); outinteger(1,nlongest);
outstring(1,", with"); outinteger(1,nel); outstring(1,"elements.");
outstring(1,"\n")
end </syntaxhighlight>
{{out}}
<pre>
sequence for 27 :
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
number of elements: 112
 
number < 100000 with the longest sequence: 77031 , with 351 elements.
</pre>
 
 
=={{header|ALGOL 68}}==
Line 460 ⟶ 577:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - using the ''print'' routine rather than ''printf''}}
<langsyntaxhighlight lang="algol68">MODE LINT = # LONG ... # INT;
 
PROC hailstone = (INT in n, REF[]LINT array)INT:
Line 506 ⟶ 623:
print(("Max",hmax," at j=",jatmax, new line))
#
)</langsyntaxhighlight>
{{out}}
<pre>
Line 512 ⟶ 629:
[ 77031, 231094, 115547, 346642, ..., 8, 4, 2, 1] len=351
Max 351 at j=77031
</pre>
 
=={{header|ALGOL-M}}==
The limitations of ALGOL-M's 15-bit integer data type will not allow the required search up to 100000 for the longest sequence, so we stick with what is possible.
<syntaxhighlight lang="algol">
BEGIN
 
INTEGER N, LEN, YES, NO, LIMIT, LONGEST, NLONG;
 
% RETURN P MOD Q %
INTEGER FUNCTION MOD(P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
 
% COMPUTE AND OPTIONALLY DISPLAY HAILSTONE SEQUENCE FOR N. %
% RETURN LENGTH OF SEQUENCE OR ZERO ON OVERFLOW. %
INTEGER FUNCTION HAILSTONE(N, DISPLAY);
INTEGER N, DISPLAY;
BEGIN
INTEGER LEN;
LEN := 1;
IF DISPLAY = 1 THEN WRITE("");
WHILE (N <> 1) AND (N > 0) DO
BEGIN
IF DISPLAY = 1 THEN WRITEON(N," ");
IF MOD(N,2) = 0 THEN
N := N / 2
ELSE
N := (N * 3) + 1;
LEN := LEN + 1;
END;
IF DISPLAY = 1 THEN WRITEON(N);
HAILSTONE := (IF N < 0 THEN 0 ELSE LEN);
END;
 
% EXERCISE THE FUNCTION %
YES := 1; NO := 0;
WRITE("DISPLAY HAILSTONE SEQUENCE FOR WHAT NUMBER?");
READ(N);
LEN := HAILSTONE(N, YES);
WRITE("SEQUENCE LENGTH =", LEN);
 
% FIND LONGEST SEQUENCE BEFORE OVERFLOW %
N := 2;
LONGEST := 1;
LEN := 2;
NLONG := 2;
LIMIT := 1000;
WRITE("SEARCHING FOR LONGEST SEQUENCE UP TO N =",LIMIT," ...");
WHILE (N < LIMIT) AND (LEN <> 0) DO
BEGIN
LEN := HAILSTONE(N, NO);
IF LEN > LONGEST THEN
BEGIN
LONGEST := LEN;
NLONG := N;
END;
N := N + 1;
END;
IF LEN = 0 THEN WRITE("SEARCH TERMINATED WITH OVERFLOW AT N =",N-1);
WRITE("MAXIMUM SEQUENCE LENGTH =", LONGEST, " FOR N =", NLONG);
 
END </syntaxhighlight>
{{out}}
<pre>
DISPLAY HAILSTONE SEQUENCE FOR WHAT NUMBER?
-> 27
27 82 41 124 62 31 94 47 142 71
214 107 322 161 484 242 121 364 182 91
274 137 412 206 103 310 155 466 233 700
350 175 526 263 790 395 1186 593 1780 890
445 1336 668 334 167 502 251 754 377 1132
566 283 850 425 1276 638 319 958 479 1438
719 2158 1079 3238 1619 4858 2429 7288 3644 1822
911 2734 1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325 976 488
244 122 61 184 92 46 23 70 35 106
53 160 80 40 20 10 5 16 8 4
2 1
SEQUENCE LENGTH = 112
SEARCHING FOR LONGEST SEQUENCE UP TO N = 10000 ...
SEARCH TERMINATED WITH OVERFLOW AT N = 447
MAXIMUM SEQUENCE LENGTH = 144 FOR N = 327</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
% show some Hailstone Sequence related information %
% calculates the length of the sequence generated by n, %
% if showFirstAndLast is true, the first and last 4 elements of the %
% sequence are stored in first and last %
% hs holds a cache of the upbHs previously calculated sequence lengths %
% if showFirstAndLast is false, the cache will be used %
procedure hailstone ( integer value n
; integer array first, last ( * )
; integer result length
; integer array hs ( * )
; integer value upbHs
; logical value showFirstAndLast
) ;
if not showFirstAndLast and n <= upbHs and hs( n ) not = 0 then begin
% no need to store the start and end of the sequence and we already %
% know the length of the sequence for n %
length := hs( n )
end
else begin
% must calculate the sequence length %
integer sv;
for i := 1 until 4 do first( i ) := last( i ) := 0;
length := 0;
sv := n;
if sv > 0 then begin
while begin
length := length + 1;
if showFirstAndLast then begin
if length <= 4 then first( length ) := sv;
for lPos := 1 until 3 do last( lPos ) := last( lPos + 1 );
last( 4 ) := sv
end
else if sv <= upbHs and hs( sv ) not = 0 then begin
% have a known value %
length := ( length + hs( sv ) ) - 1;
sv := 1
end ;
sv not = 1
end do begin
sv := if odd( sv ) then ( 3 * sv ) + 1 else sv div 2
end while_sv_ne_1 ;
if n < upbHs then hs( n ) := length
end if_sv_gt_0
end hailstone ;
begin
% test the hailstone procedure %
integer HS_CACHE_SIZE;
HS_CACHE_SIZE := 100000;
begin
integer array first, last ( 1 :: 4 );
integer length, maxLength, maxNumber;
integer array hs ( 1 :: HS_CACHE_SIZE );
for i := 1 until HS_CACHE_SIZE do hs( i ) := 0;
hailstone( 27, first, last, length, hs, HS_CACHE_SIZE, true );
write( i_w := 1, s_w := 0
, "27: length ", length, ", first: ["
, first( 1 ), " ", first( 2 ), " ", first( 3 ), " ", first( 4 )
, "] last: ["
, last( 1 ), " ", last( 2 ), " ", last( 3 ), " ", last( 4 )
, "]"
);
maxNumber := 0;
maxLength := 0;
for n := 1 until 100000 do begin
hailstone( n, first, last, length, hs, HS_CACHE_SIZE, false );
if length > maxLength then begin
maxNumber := n;
maxLength := length
end if_length_gt_maxLength
end for_n ;
write( i_w := 1, s_w := 1, "Maximum sequence length: ", maxLength, " for: ", maxNumber )
end
end
end.</syntaxhighlight>
{{out}}
<pre>
27: length 112, first: [27 82 41 124] last: [8 4 2 1]
Maximum sequence length: 351 for: 77031
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
 
#proto Hailstone(_X_,_SW_)
 
algoritmo
 
valor=27, máxima secuencia=0, vtemp=0
imprimir ( _Hailstone(27,1) ---copiar en 'máxima secuencia'--- , NL )
i=28
iterar
_Hailstone(i,0), copiar en 'vtemp'
cuando( sea mayor que 'máxima secuencia' ) {
máxima secuencia = vtemp
valor=i
}
++i
hasta que ' #(i==100000) '
imprimir ( #(utf8("Máxima longitud ")),máxima secuencia,\
" fue encontrada para Hailstone(",valor,\
#(utf8(") para números <100,000")), NL )
 
terminar
 
subrutinas
 
Hailstone(n, sw)
largo_de_secuencia = 0
v={}, n, mete(v)
iterar
tomar si ( es par(n), #(n/2), \
tomar si ( #(n<>1), #(3*n+1), 1) )
---copiar en 'n'--- mete(v)
hasta que ' #(n==1) '
#(length(v)), mover a 'largo_de_secuencia'
cuando (sw){
decimales '0'
#( v[1:4] ), ",...,",
#( v[largo_de_secuencia-4 : largo_de_secuencia] )
NL, #(utf8("Tamaño de la secuencia: "))
imprime esto; decimales normales
}
retornar ' largo_de_secuencia '
 
</syntaxhighlight>
{{out}}
<pre>
27,82,41,124,...,16,8,4,2,1
Tamaño de la secuencia: 112
Máxima longitud 351 fue encontrada para Hailstone(77031) para números <100,000
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">
<lang APL>seq←hailstone n;next
⍝ recursive dfn:
dfnHailstone←{
c←⊃⌽⍵ ⍝ last element
1=c:1 ⍝ if it is 1, stop.
⍵,∇(1+2|c)⊃(c÷2)(1+3×c) ⍝ otherwise pick the next step, and append the result of the recursive call
}
 
⍝ tradfn version:
∇seq←hailstone n;next
⍝ Returns the hailstone sequence for a given number
 
Line 524 ⟶ 870:
n←next[1+2|n] ⍝ Pick the appropriate next step
seq,←n ⍝ Append that to the sequence
:EndWhile</lang>
 
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="apl"> dfnHailstone 5
<lang APL> 5↑hailstone 27
5 16 8 4 2 1
5↑hailstone 27
27 82 41 124 62
¯5↑hailstone 27
Line 533 ⟶ 884:
112
1↑{⍵[⍒↑(⍴∘hailstone)¨⍵]}⍳100000
77031</langsyntaxhighlight>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">on hailstoneSequence(n)
script o
property sequence : {n}
end script
repeat until (n = 1)
if (n mod 2 is 0) then
set n to n div 2
else
set n to 3 * n + 1
end if
set end of o's sequence to n
end repeat
return o's sequence
end hailstoneSequence
 
set n to 27
tell hailstoneSequence(n)
return {n:n, |length of sequence|:(its length), |first 4 numbers|:items 1 thru 4, |last 4 numbers|:items -4 thru -1}
end tell</syntaxhighlight>
 
{{output}}
<pre>{|length of sequence|:112, |first 4 numbers|:{27, 82, 41, 124}, |last 4 numbers|:{8, 4, 2, 1}}</pre>
 
<syntaxhighlight lang="applescript">-- Number(s) below 100,000 giving the longest sequence length, using the hailstoneSequence(n) handler above.
set nums to {}
set longestLength to 1
repeat with n from 2 to 99999
set thisLength to (count hailstoneSequence(n))
if (thisLength < longestLength) then
else if (thisLength > longestLength) then
set nums to {n}
set longestLength to thisLength
else
set end of nums to n
end if
end repeat
return {|number(s) giving longest sequence length|:nums, |length of sequence|:longestLength}</syntaxhighlight>
 
{{output}}
<pre>{|number(s) giving longest sequence length|:{77031}, |length of sequence|:351}</pre>
 
=={{header|ARM Assembly}}==
 
Output is in hexadecimal but is otherwise correct.
Because of the Game Boy Advance's limited screen size, only the first 4 and last 4 entries are printed to the screen. The emulator's memory dump can show the rest. In addition, the task was split into two separate programs.
 
===Hailstone Sequence of N equal to 27 ===
 
<syntaxhighlight lang="arm assembly"> .org 0x08000000
 
b ProgramStart
 
;cartridge header goes here
 
 
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Program Start
 
.equ ramarea, 0x02000000
.equ CursorX,ramarea
.equ CursorY,ramarea+1
.equ hailstoneram,0x02000004
ProgramStart:
mov sp,#0x03000000 ;Init Stack Pointer
mov r4,#0x04000000 ;DISPCNT - LCD Video Controller
mov r2,#0x403 ;4= Layer 2 on / 3= ScreenMode 3
str r2,[r4] ;now the user can see the screen
 
bl ResetTextCursors ;set text cursors to top left of screen. This routine, as well as the other I/O
; routines, were omitted to keep this entry short.
mov r0,#27
adr r1,HailStoneMessage_Init
bl PrintString
bl NewLine
bl ShowHex32
bl NewLine
bl NewLine
bl Hailstone
;function is complete, return the output
adr r1,HailStoneMessage_0
bl PrintString
bl NewLine
ldr r1,HailStoneRam_Mirror ;mov r2,0x02000004
ldr r0,[r1],#4
bl ShowHex32
bl NewLine
ldr r0,[r1],#4
bl ShowHex32
bl NewLine
ldr r0,[r1],#4
bl ShowHex32
bl NewLine
ldr r0,[r1],#4
bl ShowHex32
bl NewLine
bl NewLine
adr r1,HailStoneMessage_1
bl PrintString
bl NewLine
ldr r0,[r2],#4
bl ShowHex32
bl NewLine
ldr r0,[r2],#4
bl ShowHex32
bl NewLine
ldr r0,[r2],#4
bl ShowHex32
bl NewLine
ldr r0,[r2],#4
bl ShowHex32
bl NewLine
bl NewLine
adr r1,HailStoneMessage_2
bl PrintString
bl NewLine
mov r0,r3
bl ShowHex32
 
forever:
b forever ;we're done, so trap the program counter.
Hailstone:
;input: R0 = n.
;out: r2 = pointer to last 4 entries
; r3 = length of sequence
;reg usage:
;R1 = scratchpad
;R3 = counter for entries in the sequence.
;R5 = pointer to output ram
stmfd sp!,{r4-r12,lr}
 
mov r5,#0x02000000
add r5,r5,#4
str r0,[r5],#4 ;store in hailstone ram and post-inc by 4
mov r3,#0
loop_hailstone:
add r3,r3,#1 ;represents number of entries in the sequence
cmp r0,#1
beq hailstone_end
tst r0,#1
;;;; executes only if r0 was even
moveq r0,r0,lsr #1 ;divide
;;;; executes only if r0 was odd
movne r1,r0
movne r0,r0,lsl #1
addne r0,r1,r0
addne r0,r0,#1
str r0,[r5],#4 ;store in hailstone ram, post inc by 4
b loop_hailstone
hailstone_end:
sub r5,r5,#16 ;subtract 16 to get pointer to last 4 entries.
mov r2,r5 ;output ptr to last 4 entries to r2.
;pointer to first 4 entries is 0x02000004
ldmfd sp!,{r4-r12,pc}
HailStoneRam_Mirror:
.long 0x02000004
HailstoneMessage_Init:
.byte "Your input was:",255
.align 4
HailstoneMessage_0:
.byte "First 4 numbers are:",255
.align 4
HailstoneMessage_1:
.byte "Last 4 numbers are:",255
.align 4
HailstoneMessage_2:
.byte "Sequence length is:",255
.align 4
 
;;;;;;;;;;; EVERYTHING PAST THIS POINT IS JUST I/O ROUTINES FOR PRINTING NUMBERS AND WORDS TO THE GAME BOY ADVANCE'S SCREEN
;;;;;;;;;;; I ASSURE YOU THAT ALL OF IT WORKS BUT CHANCES ARE YOU DIDN'T COME HERE TO SEE THAT.
;;;;;;;;;;; THANKS TO KEITH OF CHIBIAKUMAS.COM FOR WRITING THEM!</syntaxhighlight>
 
{{out}}
<pre>
Your input was:
0000001B
 
First 4 numbers are:
0000001B
00000052
00000029
0000007C
 
Last 4 numbers are:
00000008
00000004
00000002
00000001
 
Sequence length is:
00000070
</pre>
 
[https://ibb.co/WzgWjZ9 Picture of output on VisualBoyAdvance screen]
 
 
===Biggest Sequence Between 2 and 100,000===
To keep this short, I'm only including the part that changed, and the output. This goes after the call to <code>ResetTextCursors</code> but before the infinite loop:
 
<syntaxhighlight lang="arm assembly"> mov r0,#1
bl Hailstone
mov r6,r3
mov r0,#2
mov r8,#100000
loop_getBiggestHailstone:
mov r10,r0
bl Hailstone
mov r0,r10
cmp r3,r6
movgt r6,r3 ;if greater than, store in r6
movgt r7,r0 ;if greater than, store in r7
add r0,r0,#1
cmp r0,r8
blt loop_getBiggestHailstone
adr r1,HailstoneMessage_0
bl PrintString
bl NewLine
adr r1,HailStoneMessage_1
bl PrintString
bl NewLine
mov r0,r7
bl ShowHex32
bl NewLine
adr r1,HailStoneMessage_2
bl PrintString
bl NewLine
mov r0,r6
bl ShowHex32
bl NewLine</syntaxhighlight>
 
{{out}}
<pre>
The number that makes the
biggest sequence is:
00012CE7
And that sequence has a length
of:
0000015F
</pre>
 
[https://ibb.co/hXm7cJ3 Output of second program on VisualBoyAdvance's screen]
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">hailstone: function [n][
ret: @[n]
while [n>1][
if? 1 = and n 1 -> n: 1+3*n
else -> n: n/2
 
'ret ++ n
]
ret
]
 
print "Hailstone sequence for 27:"
print hailstone 27
 
maxHailstoneLength: 0
maxHailstone: 0
 
loop 2..1000 'x [
l: size hailstone x
if l>maxHailstoneLength [
maxHailstoneLength: l
maxHailstone: x
]
]
 
print ["max hailstone sequence found (<100000): of length" maxHailstoneLength "for" maxHailstone]
</syntaxhighlight>
 
{{out}}
 
<pre>Hailstone sequence for 27:
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
max hailstone sequence found (<100000): of length 351 for 77031
</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">; Submitted by MasterFocus --- http://tiny.cc/iTunis
 
; [1] Generate the Hailstone Seq. for a number
Line 575 ⟶ 1,245:
}
ToolTip
MsgBox % "Number: " MaxNum "`nCount: " Max</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
 
<langsyntaxhighlight lang="autoit">
$Hail = Hailstone(27)
ConsoleWrite("Sequence-Lenght: "&$Hail&@CRLF)
Line 608 ⟶ 1,279:
Return $Counter
EndFunc ;==>Hailstone
</syntaxhighlight>
</lang>
{{out}}
<pre>27,82,41,124,62,31,94,47,142,71,214,107,322,161,484,242,121,364,182,91,274,137,412,206,103,
Line 620 ⟶ 1,291:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">
#!/usr/bin/awk -f
function hailstone(v, verbose) {
Line 650 ⟶ 1,321:
printf("longest hailstone sequence is %i and has %i elements\n",ix,m);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 660 ⟶ 1,331:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 HOME
 
100 N = 27
Line 691 ⟶ 1,362:
470 IF EVEN THEN N=N/2
480 IF NOT EVEN THEN N = (3 * N) + 1
490 NEXT L : STOP</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> seqlen% = FNhailstone(27, TRUE)
PRINT '"Sequence length = "; seqlen%
maxlen% = 0
Line 716 ⟶ 1,387:
L% += 1
ENDWHILE
= L% + 1</langsyntaxhighlight>
{{out}}
<pre>
Line 740 ⟶ 1,411:
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight QBASIClang="qbasic">100 PRINT : PRINT "HAILSTONE SEQUENCE FOR N = 27:"
110 N=27 : SHOW=1
120 GOSUB 1000
Line 763 ⟶ 1,434:
1060 S = 3*S+1
1070 GOTO 1020
</syntaxhighlight>
</lang>
==={{header|FreeBASIC}}===
<langsyntaxhighlight FreeBASIClang="freebasic">' version 17-06-2015
' compile with: fbc -s console
 
Line 855 ⟶ 1,526:
Print : Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>sequence for number 27
Line 874 ⟶ 1,545:
-------------------------------------------------------------------------------
The longest sequence is for 77031, it has a sequence length of 351</pre>
 
==={{header|GW-BASIC}}===
<syntaxhighlight lang="gwbasic">10 N# = 27
20 P = 1
30 GOSUB 130
40 PRINT "That took";C;"steps."
50 P = 0 : A = 0 : B = 0
60 FOR M = 1 TO 99999!
70 N# = M
80 GOSUB 130
90 IF C > B THEN B = C: A = M
100 NEXT M
110 PRINT "The longest sequence is for n=";A;" and is ";B;" steps long."
120 END
130 C = 1
140 IF P = 1 THEN PRINT N#
150 IF N# < 2 THEN RETURN
160 IF N#/2 = INT(N#/2) THEN N# = N#/2 ELSE N# = 3*N# + 1
170 C = C + 1
180 GOTO 140</syntaxhighlight>
 
==={{header|Liberty BASIC}}===
<langsyntaxhighlight lang="lb">print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
while hailstone < 1 or hailstone <> int(hailstone)
Line 927 ⟶ 1,618:
print ""
print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"."
end</langsyntaxhighlight>
 
==={{header|OxygenBasic}}===
<langsyntaxhighlight lang="oxygenbasic">
 
function Hailstone(sys *n)
Line 969 ⟶ 1,660:
 
'result 100000, 77031, 351
</syntaxhighlight>
</lang>
 
==={{header|PureBasic}}===
<langsyntaxhighlight PureBasiclang="purebasic">NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array
 
Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list
Line 1,019 ⟶ 1,710:
Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
{{out}}
Line 1,050 ⟶ 1,741:
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang="runbasic">print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
Line 1,089 ⟶ 1,780:
end if
wend
END FUNCTION</langsyntaxhighlight>
 
==={{header|Tiny BASIC}}===
Tiny BASIC is limited to signed integers from -32768 to 32767. This code combines two integers into one: number = 32766A + B, to emulate integers up to 1.07 billion. Dealing with integer truncation, carries, and avoiding overflows requires some finesse. Even so one number, namely 77671, causes an overflow because one of its steps exceeds 1.07 billion.
 
<syntaxhighlight lang="text"> PRINT "Enter a positive integer"
INPUT N REM unit column
LET M = 0 REM 32766 column
LET C = 1 REM count
LET P = 1 REM print the sequence?
LET L = 1 REM finite state label
GOSUB 10
LET F = 1 REM current champion
LET E = 0 REM 32766 part of current champ
LET Y = 1 REM length of current longest sequence
LET P = 0 REM no more printing
LET W = 0 REM currently testing this number
LET V = 0 REM 32766 column of the number
PRINT "Testing for longest chain for n<100000..."
5 LET W = W + 1
REM PRINT V, " ", W
LET N = W
LET M = V
LET C = 1 REM reset count
IF W = 32766 THEN GOSUB 50
GOSUB 10
IF C > Y THEN GOSUB 60
IF V = 3 THEN IF W = 1702 THEN GOTO 8
GOTO 5
8 PRINT "The longest sequence starts at 32766x",E," + ",F
PRINT "And goes for ",Y," steps."
END
10 IF P = 1 THEN IF M > 0 THEN PRINT C," 32766x",M," + ",N
IF P = 1 THEN IF M = 0 THEN PRINT C," ",N
IF M = 0 THEN IF N = 1 THEN RETURN
LET C = C + 1
IF 2*(N/2)=N THEN GOTO 20
IF M > 10922 THEN GOTO 100
IF N > 21844 THEN GOTO 30
IF N > 10922 THEN GOTO 40
 
LET N = 3*N + 1
LET M = 3*M
GOTO 10
20 LET N = N/2
IF (M/2)*2<>M THEN LET N = N + 16383 REM account for integer truncation
LET M=M/2
GOTO 10
 
30 LET N = N - 21844 REM two ways of accounting for overflow
LET N = 3*N + 1
LET M = 3*M + 2
GOTO 10
40 LET N = N - 10922
LET N = 3*N + 1
LET M = 3*M + 1
GOTO 10
50 LET W = 0 REM addition with carry
LET V = V + 1
RETURN
60 LET Y = C REM tracking current champion
LET F = W
LET E = V
RETURN
 
100 PRINT "Uh oh, getting an overflow for 32766x",V," + ",W
PRINT "at step number ",C
PRINT "trying to triple 32766x",M," + ",N
RETURN</syntaxhighlight>
{{out}}
<pre>
Enter a positive integer
27
1 27
2 82
3 41
....
110 4
111 2
112 1
Testing for longest chain for n<100000...
Uh oh, getting an overflow for 32766x2 + 12139
at step number 72
trying to triple 32766x15980 + 7565
The longest sequence starts at 32766x2 + 11499
And goes for 351 steps.</pre>
 
=={{header|Batch File}}==
Line 1,095 ⟶ 1,876:
''2. Show that the hailstone sequence for the number 27 has 112 elements... ''
<!--The third task is NOT included because task #3 will take several hours in processing...-->
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
echo.
Line 1,135 ⟶ 1,916:
set /a num/=2
set seq=!seq! %num%
goto loop</langsyntaxhighlight>
{{Out}}
<pre>Task #1: (Start:111)
Line 1,148 ⟶ 1,929:
 
The script above could only be used in '''smaller''' inputs. Thus, for the third task, a slightly different script will be used. However, this script is still '''slow'''. I tried this on a fast computer and it took about 40-45 minutes to complete.
<langsyntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
if "%~1"=="test" (
Line 1,170 ⟶ 1,951:
pause>nul
 
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>Number less than 100000 with longest sequence: 77031
With length 351.</pre>
 
 
=={{header|beeswax}}==
Line 1,182 ⟶ 1,962:
'''The pure hailstone sequence function''', returning the sequence for any number entered in the console:
 
<langsyntaxhighlight lang="beeswax"> >@:N q
>%"d3~@.PNp
d~2~pL~1F{<T_</langsyntaxhighlight>
 
'''Returning the sequence for the starting value <code>27</code>'''
 
<langsyntaxhighlight lang="beeswax"> >@:N q
>%"d3~@.PNq
d~2~qL~1Ff{<BF3_
{NNgA<</langsyntaxhighlight>
 
Output of the sequence, followed by the length of the sequence:
 
<syntaxhighlight lang="text">
27
82
Line 1,225 ⟶ 2,005:
1
 
112</langsyntaxhighlight>
 
'''Number below 100,000 with the longest hailstone sequence, and the length of that sequence:'''
 
<langsyntaxhighlight lang="beeswax"> >@: q pf1_#
>%"d3~@.Pqf#{g?` `{gpK@~BP9~5@P@q'M<
d~2~pL~1Ff< < >?d
>zAg?MM@1~y@~gLpz2~yg@~3~hAg?M d
>?~fz1~y?yg@hhAg?Mb</langsyntaxhighlight>
 
Output:
 
<syntaxhighlight lang="text">77031 351</langsyntaxhighlight>
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">93*:. v
> :2%v >
v+1*3_2/
Line 1,258 ⟶ 2,038:
vg01g00 ,+49<
>"@"*+.@
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,265 ⟶ 2,045:
77031
351</pre>
 
=={{header|BQN}}==
Works in: [[CBQN]]
<syntaxhighlight lang="bqn">Collatz ← ⥊⊸{
𝕨𝕊1: 𝕨;
(𝕨⊸∾ 𝕊 ⊢) (2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩
}
 
Collatz1 ← ⌽∘{
1: ⟨1⟩;
𝕩∾˜𝕊(2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩
}
 
•Show Collatz1 5
 
•Show (⊑∾≠){𝕩⊑˜⊑⍒≠¨𝕩}Collatz1¨1+↕99999</syntaxhighlight>
<syntaxhighlight lang="bqn">⟨ 5 16 8 4 2 1 ⟩
⟨ 77031 351 ⟩</syntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(
( hailstone
= L len
Line 1,309 ⟶ 2,107:
)
)
);</langsyntaxhighlight>
 
=={{header|Brainf***}}==
{{incomplete}}
<syntaxhighlight lang="brainf***">>>>>>>,>,>,<<
Prints the number of terms required to map the input to 1. Does not count the first term of the sequence.
 
<lang Brainf***>>,[
[
.[-<+>]
]
>
[
.[-<+>]
]
>
[
.[-<+>]
]
<<<<
 
 
>------------------------------------------------[<<+>>-]>
[
<<<
[<+>-]<
[>++++++++++<-]>
>>>
------------------------------------------------
[<<<+>>>-]>
[
----------[<<<<
>>>[>>>>]+[[-]+<[->>>>++>>>>+[>>>>]++[->+<<<<<]]<<<]
[>++++++++[>------<-]>--[>>[->>>>]+>+[<<<<-]>-],<
]>>>>
------------------------------------------------
]>>>++>+>>[
[<<[>>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<<]]<[>+<>-]>]
]
>[>[>>>>]+[[-]<[+[->>>>]>+<]>[<+>[<<<<]]+<<<<]>>>[->>>>]+>+[<<<<]]
<
>[[>+>>[<<<<+>>>>-]>]<<<<[-]>[-<<<<]]>>>>>>>
 
]>>+[[-]++++++>>>>]<<<<[[<++++++++>-]<.[-]<[-]<[-]<]<,
<<<[>+<<<+>>-]>[-<+>]>>>>>>>>>++++[>+++++++++++<-]++++[>>++++++++<<-]<<<<<<<<<<
]</lang>
 
<lang Brainf***>27
[
111</lang>
>>>>>>>>>>+>.>.<<<<<<<<<<<<
>>+>+<<<
[-[->]<]+
>>>[>]
<[-<]<[-]<
 
[>+>+<<-]>[<+>-]+
>[
<<<[->>>>+>+>+<<<<<<]>>>>>>
[-<<<<<<+>>>>>>]<[-<<<<<+>>>>>]<[-<<<<+>>>>]
<<<<+>>
-
>[-]]
<<[-]>[
<<[-<+>[-<->>>>>+>]<<<<<]>>>>[-<<<<+>>>>]<<
-]
 
<<[->+>+<<]>[-<+>]>
[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]
++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[.[-]<]<
-[+>]<
]
 
[This program never terminates! ]
[This program isn't complete, (it only prints the hailstone ]
[sequence of a number until 1) but it may help other people ]
[to make complete versions. ]
[ ]
[This program only takes in up to 3 digit numbers as input ]
[If you want to input 1 digit integers, add a 0 before. e.g ]
[04. ]
[ ]
[Summary: ]
[This program takes 16 memory cells of space. Their data is ]
[presented below: ]
[ ]
[Cell 0: Temp cell. ]
[Cell 1: Displays the current number. This changes based on ]
[Collatz' Conjecture. ]
[Cell 14: Displays length of the hailstone sequence. ]
[Cell 15: ASCII code for ",". ]
[Cell 16: ASCII code for " " (Space). ]
[Rest of the cells: Temp cells. ]
</syntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">hailstone = { num |
sequence = [num]
while { num != 1 }
Line 1,362 ⟶ 2,228:
}
 
p "Longest was starting from #{longest[:number]} and was of length #{longest[:length]}"</langsyntaxhighlight>
{{out}}
<pre>Sequence for 27 is correct
Line 1,372 ⟶ 2,238:
Longest so far: 77031 @ 351 elements
Longest was starting from 77031 and was of length 351</pre>
 
=={{header|Bruijn}}==
 
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/List .
:import std/Math M
:import std/Number/Binary .
 
# hailstone sequence using binary shifts
hailstone y [[(0 =? (+1b)) {}0 go]]
go 0 : (=²?0 (1 /²0) (1 (↑¹0 + 0)))
 
# --- tests ---
 
seq-27 hailstone (+27b)
 
:test (∀seq-27) ((+112))
:test (take (+4) seq-27) ((+27b) : ((+82b) : ((+41b) : {}(+124b))))
:test (take (+4) <~>seq-27) ((+1b) : ((+2b) : ((+4b) : {}(+8b))))
 
below-100000 [0 : ∀(hailstone 0)] <$> seq
seq take (+99999) (iterate ++‣ (+1b))
 
main [head (max-by (M.compare ⋔ tail) below-100000)]
</syntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) 27{^^^^2.%{3.*1.+}\/{2./}\/ie}{1!=}w!bx{\/+]}{\/isn!}w!L[
112
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 1,421 ⟶ 2,313:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>[ 27, 82, 41, 124, ...., 8, 4, 2, 1] len= 112
Line 1,428 ⟶ 2,320:
===With caching===
Much faster if you want to go over a million or so.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define N 10000000
Line 1,458 ⟶ 2,350:
printf("max below %d: %d, length %d\n", N, mi, max);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,504 ⟶ 2,396:
}
}
}</langsyntaxhighlight>
<pre>
112 Elements
Line 1,513 ⟶ 2,405:
===With caching===
As with the [[#C|C example]], much faster if you want to go over a million or so.
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 1,554 ⟶ 2,446:
}
}
}</langsyntaxhighlight>
<pre>
max below 100000: 77031 (351 steps)
Line 1,560 ⟶ 2,452:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <vector>
#include <utility>
Line 1,609 ⟶ 2,501:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,616 ⟶ 2,508:
last four elements of hailstone(27) are 8 4 2 1
the longest hailstone sequence under 100,000 is 77031 with 351 elements.
</pre>
 
=== {{libheader|Qt}} ===
{{uses from|library|Qt}}
Templated solution works for all of Qt's sequential container classes (QLinkedList, QList, QVector).
<syntaxhighlight lang="cpp">
#include <QDebug>
#include <QVector>
 
template <class T>
T hailstone(typename T::value_type n)
{
T seq;
for (seq << n; n != 1; seq << n) {
n = (n&1) ? (3*n)+1 : n/2;
}
return seq;
}
 
template <class T>
T longest_hailstone_seq(typename T::value_type n)
{
T maxSeq;
for (; n > 0; --n) {
const auto seq = hailstone<T>(n);
if (seq.size() > maxSeq.size()) {
maxSeq = seq;
}
}
return maxSeq;
}
 
int main(int, char *[]) {
const auto seq = hailstone<QVector<uint_fast16_t>>(27);
qInfo() << "hailstone(27):";
qInfo() << " length:" << seq.size() << "elements";
qInfo() << " first 4 elements:" << seq.mid(0,4);
qInfo() << " last 4 elements:" << seq.mid(seq.size()-4);
 
const auto max = longest_hailstone_seq<QVector<uint_fast32_t>>(100000);
qInfo() << "longest sequence with starting element under 100000:";
qInfo() << " length:" << max.size() << "elements";
qInfo() << " starting element:" << max.first();
}
</syntaxhighlight>
{{out}}
<pre>
hailstone(27):
length: 112 elements
first 4 elements: QVector(27, 82, 41, 124)
last 4 elements: QVector(8, 4, 2, 1)
longest sequence with starting element under 100000:
length: 351 elements
starting element: 77031
</pre>
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
{Integer*} hailstone(variable Integer n) {
Line 1,641 ⟶ 2,587:
}
print("the longest sequence under 100,000 starts with ``longest.first else "what?"`` and has length ``longest.size``");
}</langsyntaxhighlight>
 
=={{header|CLIPS}}==
<langsyntaxhighlight lang="clips">(deftemplate longest
(slot bound) ; upper bound for the range of values to check
(slot next (default 2)) ; next value that needs to be checked
Line 1,719 ⟶ 2,665:
(printout t "sequence is " ?start " with a length of " ?len "." crlf)
(printout t crlf)
)</langsyntaxhighlight>
 
{{out}}
Line 1,731 ⟶ 2,677:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn hailstone-seq [n]
{:pre [(pos? n)]}
(lazy-seq
Line 1,747 ⟶ 2,693:
(for [i (range 1 100000)]
{:num i, :len (count (hailstone-seq i))}))]
(println "Maximum length" max-len "was found for hailstone(" max-i ")."))</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight 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</syntaxhighlight>
{{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}}==
Testing with GnuCOBOL
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. hailstones.
remarks. cobc -x hailstones.cob.
Line 1,840 ⟶ 2,847:
.
 
end program hailstones.</langsyntaxhighlight>
 
{{out}}
Line 1,855 ⟶ 2,862:
=={{header|CoffeeScript}}==
Recursive version:
<langsyntaxhighlight lang="coffeescript">hailstone = (n) ->
if n is 1
[n]
Line 1,880 ⟶ 2,887:
maxnums = [i]
console.log "Max length: #{maxlength}; numbers generating sequences of this length: #{maxnums}"</langsyntaxhighlight>
<pre>hailstone(27) = 27,82,41,124 ... 8,4,2,1 (length: 112)
Max length: 351; numbers generating sequences of this length: 77031</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun hailstone (n)
(cond ((= n 1) '(1))
((evenp n) (cons n (hailstone (/ n 2))))
Line 1,895 ⟶ 2,902:
(let ((len (length (hailstone i))))
(when (> len l) (setq l len k i)))
finally (format t "Longest hailstone sequence under ~A for ~A, having length ~A." n k l))))</langsyntaxhighlight>
Sample session:
<pre>ROSETTA> (length (hailstone 27))
Line 1,906 ⟶ 2,913:
Longest hailstone sequence under 100000 for 77031, having length 351.
NIL</pre>
 
=={{header|Cowgol}}==
<syntaxhighlight lang="cowgol">include "cowgol.coh";
 
# Generate the hailstone sequence for the given N and return the length.
# If a non-NULL pointer to a buffer is given, then store the sequence there.
sub hailstone(n: uint32, buf: [uint32]): (len: uint32) is
len := 0;
loop
if buf != 0 as [uint32] then
[buf] := n;
buf := @next buf;
end if;
len := len + 1;
if n == 1 then
break;
elseif n & 1 == 0 then
n := n / 2;
else
n := 3*n + 1;
end if;
end loop;
end sub;
 
# Generate hailstone sequence for 27
var h27: uint32[113];
var h27len := hailstone(27, &h27[0]);
 
# Print information about it
print("The hailstone sequence for 27 has ");
print_i32(h27len);
print(" elements.\nThe first 4 elements are:");
var n: @indexof h27 := 0;
while n < 4 loop
print_char(' ');
print_i32(h27[n]);
n := n + 1;
end loop;
print(", and the last 4 elements are:");
n := h27len as @indexof h27 - 4;
while n as uint32 < h27len loop
print_char(' ');
print_i32(h27[n]);
n := n + 1;
end loop
print(".\n");
 
# Find longest hailstone sequence < 100,000
var i: uint32 := 1;
var max_i := i;
var len: uint32 := 0;
var max_len := len;
while i < 100000 loop
len := hailstone(i, 0 as [uint32]);
if len > max_len then
max_i := i;
max_len := len;
end if;
i := i + 1;
end loop;
 
print_i32(max_i);
print(" has the longest hailstone sequence < 100000: ");
print_i32(max_len);
print_nl();</syntaxhighlight>
 
{{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|Crystal}}==
<syntaxhighlight lang="ruby">
def hailstone(n)
seq = [n]
until n == 1
n = n.even? ? n // 2 : n * 3 + 1
seq << n
end
seq
end
 
max_len = (1...100_000).max_by{|n| hailstone(n).size }
max = hailstone(max_len)
puts ([max_len, max.size, max.max, max.first(4), max.last(4)])
# => [77031, 351, 21933016, [77031, 231094, 115547, 346642], [8, 4, 2, 1]]
 
twenty_seven = hailstone(27)
puts ([twenty_seven.size, twenty_seven.first(4), max.last(4)])
# => [112, [27, 82, 41, 124], [8, 4, 2, 1]]
</syntaxhighlight>
 
=={{header|D}}==
===Basic Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;
 
auto hailstone(uint n) pure nothrow {
Line 1,931 ⟶ 3,029:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
{{out}}
<pre>hailstone(27)= [27, 82, 41, 124] ... [8, 4, 2, 1]
Line 1,939 ⟶ 3,037:
===Lazy Version===
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.range;
 
auto hailstone(uint m) pure nothrow @nogc {
Line 1,958 ⟶ 3,056:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
===Faster Lazy Version===
Same output.
<langsyntaxhighlight lang="d">struct Hailstone {
uint n;
bool empty() const pure nothrow @nogc { return n == 0; }
Line 1,984 ⟶ 3,082:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
===Lazy Version With Caching===
Faster, same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;
 
struct Hailstone(size_t cacheSize = 500_000) {
Line 2,020 ⟶ 3,118:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
===Generator Range Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons, std.concurrency;
 
auto hailstone(size_t n) {
Line 2,046 ⟶ 3,144:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">
<lang dart>List<int> hailstone(int n) {
import 'package:collection/collection.dart';
if(n<=0) {
import 'dart:collection';
throw new IllegalArgumentException("start value must be >=1)");
List<int> hailstone(int n) {
if(n <= 0) {
throw ArgumentError("start value must be >=1)");
}
Queue<int>var seq =new Queue<int>();
seq.add(n);
while(n != 1) {
n = n%2 == 0 ?( n ~/ 2).toInt() : 3 * n + 1;
seq.add(n);
}
return new List<int>seq.fromtoList(seq);
}
 
// apparently List is missing toString()
String iterableToString(Iterable seq) {
String str="[";
Iterator i=seq.iterator();
while(i.hasNext()) {
str+=i.next();
if(i.hasNext()) {
str+=",";
}
}
return str+"]";
}
 
main() {
for(int i = 1; i <= 10; i++) {
print("h($i) ="+iterableToString( ${hailstone(i))}");
}
List<int>var h27 = hailstone(27);
List<int>var first4 = h27.getRangetake(0,4).toList();
print("first 4 elements of h(27): "+iterableToString($first4)");
Expectassert(ListEquality().listEqualsequals([27, 82, 41, 124], first4));
 
List<int>var last4 = h27.getRangeskip(h27.length - 4,).take(4).toList();
print("last 4 elements of h(27): "+iterableToString($last4)");
Expectassert(ListEquality().listEqualsequals([8, 4, 2, 1], last4));
 
print("length of sequence h(27): "+${h27.length}");
Expect.equalsassert(112, == h27.length);
 
int seq = 0, max = 0;
for(int i = 1; i <= 100000; i++) {
List<int>var h = hailstone(i);
if(h.length > max) {
max = h.length;
seq = i;
}
}
print("up to 100000 the sequence h($seq) has the largest length ($max)");
}
}</lang>
</syntaxhighlight>
{{out}}
<pre>h(1) = [1]
h(2) = [2, 1]
h(3) = [3, 10, 5, 16, 8, 4, 2, 1]
h(4) = [4, 2, 1]
h(5) = [5, 16, 8, 4, 2, 1]
h(6) = [6, 3, 10, 5, 16, 8, 4, 2, 1]
h(7) = [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
h(8) = [8, 4, 2, 1]
h(9) = [9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
h(10) = [10, 5, 16, 8, 4, 2, 1]
first 4 elements of h(27): [27, 82, 41, 124]
last 4 elements of h(27): [8, 4, 2, 1]
length of sequence h(27): 112
up to 100000 the sequence h(77031) has the largest length (351)</pre>
 
=={{header|Dc}}==
Firstly, this code takes the value from the stack, computes and prints the corresponding Hailstone sequence, and the length of the sequence.
Line 2,120 ⟶ 3,211:
The e and o procedure is for even and odd number respectively.
The x procedure is for overall control.
<syntaxhighlight lang="dc">27
<lang Dc>27
[[--: ]nzpq]sq
[d 2/ p]se
[d 3*1+ p]so
[d2% 0=e d1=q d2% 1=o d1=q lxx]dsxx</langsyntaxhighlight>
{{out}}
<pre>
Line 2,142 ⟶ 3,233:
Register L for the length of the longest sequence and T for the corresponding number.
Also, procedure q is slightly modified for storing L and T if needed, and all printouts in procedure e and o are muted.
<langsyntaxhighlight Dclang="dc">0dsLsT1st
[dsLltsT]sM
[[zdlL<M q]sq
Line 2,150 ⟶ 3,241:
[lt1+dstlsxc lt100000>l]dslx
lTn[:]nlLp
</syntaxhighlight>
</lang>
{{out}} (Takes quite some time on a decent machine)
<pre>77031:351</pre>
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ n = f$integer( p1 )
$ i = 1
$ loop:
Line 2,176 ⟶ 3,268:
$ write sys$output "sequence has ", i, " elements starting with ", s1, ", ", s2, ", ", s3, ", ", s4, " and ending with ", s'preantepenultimate_i, ", ", s'antepenultimate_i, ", ", s'penultimate_i, ", ", s'i
$ endif
$ sequence_length == i</langsyntaxhighlight>
{{out}}
<pre>$ @hailstone 27
sequence has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1</pre>
<langsyntaxhighlight DCLlang="dcl">$ limit = f$integer( p1 )
$ i = 1
$ max_so_far = 0
Line 2,220 ⟶ 3,312:
$ sequence_length == I
$ exit
$ endsubroutine</langsyntaxhighlight>
{{out}}
<pre>$ @longest_hailstone 100000
77031 is the number less than 100000 which has the longest hailstone sequence which is 351 in length</pre>
 
=={{header|Déjà Vu}}==
<lang dejavu>local hailstone:
swap [ over ]
while < 1 dup:
if % over 2:
#odd
++ * 3
else:
#even
/ swap 2
swap push-through rot dup
drop
if = (name) :(main):
local :h27 hailstone 27
!. = 112 len h27
!. = 27 h27! 0
!. = 82 h27! 1
!. = 41 h27! 2
!. = 124 h27! 3
!. = 8 h27! 108
!. = 4 h27! 109
!. = 2 h27! 110
!. = 1 h27! 111
local :max 0
local :maxlen 0
for i range 1 99999:
dup len hailstone i
if < maxlen:
set :maxlen
set :max i
else:
drop
!print( "number: " to-str max ", length: " to-str maxlen )
else:
@hailstone</lang>
{{out}}
<pre>true
true
true
true
true
true
true
true
true
number: 77031, length: 351</pre>
=={{header|Delphi}}==
 
<lang Delphi>program ShowHailstoneSequence;
=== Using List<Integer> ===
 
<syntaxhighlight lang="delphi">program ShowHailstoneSequence;
 
{$APPTYPE CONSOLE}
Line 2,329 ⟶ 3,377:
 
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>27: 112 elements
Line 2,335 ⟶ 3,383:
 
Longest sequence under 100,000: 77031 with 351 elements</pre>
 
=== Using Boost.Algorithm and TParallel.For ===
{{libheader| System.SysUtils}}
{{libheader| System.Types}}
{{libheader| System.Threading}}
{{libheader| System.SyncObjs}}
{{libheader| Boost.Algorithm}}
{{libheader| Boost.Int}}[https://github.com/MaiconSoft/DelphiBoostLib]
{{libheader| System.Diagnostics}}
<syntaxhighlight lang="delphi">
program ShowHailstoneSequence;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Types,
System.Threading,
System.SyncObjs,
Boost.Algorithm,
Boost.Int,
System.Diagnostics;
 
var
lList: TIntegerDynArray;
lMaxSequence, lMaxLength, i: Integer;
StopWatch: TStopwatch;
 
begin
lList := Hailstone(27);
Writeln(Format('27: %d elements', [lList.Count]));
Writeln(lList.toString(4), #10);
 
lMaxSequence := 0;
lMaxLength := 0;
 
StopWatch := TStopwatch.Create;
StopWatch.Start;
 
TParallel.for (1, 1, 100000,
procedure(idx: Integer)
var
lList: TIntegerDynArray;
begin
lList := Hailstone(idx);
if lList.Count > lMaxLength then
begin
TInterlocked.Exchange(lMaxSequence, idx);
TInterlocked.Exchange(lMaxLength, lList.Count);
end;
end);
 
StopWatch.Stop;
 
Write(Format('Longest sequence under 100,000: %d with %d elements', [lMaxSequence,
lMaxLength]));
 
Writeln(Format(' in %d ms', [StopWatch.ElapsedMilliseconds]));
 
Readln;
end.
 
</syntaxhighlight>
 
{{out}}
<pre>
27: 112 elements
[27, 82, 41, 124 ... 8, 4, 2, 1]
 
Longest sequence under 100,000: 77031 with 351 elements in 520 ms
</pre>
 
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">local hailstone:
swap [ over ]
while < 1 dup:
if % over 2:
#odd
++ * 3
else:
#even
/ swap 2
swap push-through rot dup
drop
if = (name) :(main):
local :h27 hailstone 27
!. = 112 len h27
!. = 27 h27! 0
!. = 82 h27! 1
!. = 41 h27! 2
!. = 124 h27! 3
!. = 8 h27! 108
!. = 4 h27! 109
!. = 2 h27! 110
!. = 1 h27! 111
local :max 0
local :maxlen 0
for i range 1 99999:
dup len hailstone i
if < maxlen:
set :maxlen
set :max i
else:
drop
!print( "number: " to-str max ", length: " to-str maxlen )
else:
@hailstone</syntaxhighlight>
{{out}}
<pre>true
true
true
true
true
true
true
true
true
number: 77031, length: 351</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
proc hailstone n . list[] .
list[] = [ ]
while n <> 1
list[] &= n
if n mod 2 = 0
n = n / 2
else
n = 3 * n + 1
.
.
list[] &= 1
.
hailstone 27 l[]
write "27 has length " & len l[] & " with "
for i to 4
write l[i] & " "
.
write "... "
for i = len l[] - 3 to len l[]
write l[i] & " "
.
print ""
for i = 1 to 100000
hailstone i l[]
if len l[] >= max_iter
max_i = i
max_iter = len l[]
end
end
print max_i & " has length " & max_iter
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'hash)
(lib 'sequences)
Line 2,367 ⟶ 3,569:
(writeln 'maxlength= hmaxlength 'for hmaxseed))
 
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(define H27 (iterator/f hailstone 27))
(take H27 6)
Line 2,403 ⟶ 3,605:
maxlength= 525 for 837799
 
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
This program uses no optimization, and is best run on a fast simulator.
Even with the storage-related code cut out, Part 2 of the task executes 182 million EDSAC orders.
At 650 orders per second, the original EDSAC would have taken 78 hours.
<syntaxhighlight lang="edsac">
[Hailstone (or Collatz) task for Rosetta Code.
EDSAC program, Initial Orders 2.]
 
[This program shows how subroutines can be called via the
phi, H, N, ..., V parameters, so that the code doesn't have
to be changed if the subroutines are moved about in store.
See Wilkes, Wheeler and Gill, 1951 edition, page 18.]
 
[Library subroutine P7, prints long strictly positive integer;
10 characters, right justified, padded left with spaces.
Input: 0D = integer to be printed.
Closed, even; 35 storage locations; working position 4D.]
T 55 K [call subroutine via V parameter]
P 56 F [address of subroutine]
E 25 K
T V
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F
T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
 
[Subroutine to print a string placed after the subroutine call.
One location per character, with character in top 5 bits.
Last character flagged by having bit 0 set.
17 locations, workspace 0F.]
T 54 K [call subroutine via C parameter]
P 91 F [address of subroutine]
E 25 K
T C
GKH16@A2FG4@A6@A2FT6@AFTFOFCFSFE3@A6@A3FT15@EFV2047F
 
[************ Rosetta Code task ************
Subroutine to generate and optionally store the hailstone
(Collatz) sequence for the passed-in initial term n.
Input: 4D = n, 35-bit positive integer
6F = start address of sequence if stored;
must be even; 0 = don't store
Output: 7F = number of terms in sequence, or -1 if error
Workspace: 0D (general), 8D (term of sequence)
Must be loaded at an even address.]
T 45 K [call subroutine via H parameter]
P 108 F [address of subroutine]
E 25 K
T H
G K
A 3 F
T 46 @
H 54#@ [mult reg := 1 to test odd/even]
A 4 D [load n passed in by caller]
T 8 D [term := n]
A 54 @ [load 1 (single)]
T 7 F [include initial term in count]
A 6 F [load address for store]
S 56 @ [test for 0; allow for pre-inc]
G 11 @ [skip next if storing not wanted]
A 12 @ [make 'T addr D' order]
[11] T 21 @ [plant T order, or -ve value if not storing
(note that a T order is +ve as an integer)]
[Loop: deal with current term in sequence
First store it, if user requested that]
[12] T D [clear acc; also serves to make 'T addr D' order]
A 21 @ [load T order to store term]
G 22 @ [jump if caller doesn't want store]
A 56 @ [pre-inc the address]
U 21 @ [update T order]
S 51 @ [check not gone beyond max EDSAC address]
E 47 @ [error exit if it has]
T F [clear acc]
A 8 D [load term]
[21] T D [store]
[22] T F [clear acc]
A 54#@ [load 1 (double)]
S 8 D [1 - term]
E 46 @ [if term = 1, jump out with acc = 0]
T F [clear acc]
C 8 D [acc := term AND 1]
S 54#@ [test whether 0 or 1]
G 38 @ [jump if term is even]
[Here if term is odd; acc = 0]
A 8 D [load term]
S 52#@ [guard against numeric overflow]
E 47 @ [jump if overflow]
A 52#@ [restore term after test]
L D [term*2]
A 8 D [term*3]
A 54#@ [plus 1]
E 41 @ [join common code]
[Here if term is even]
[38] T F [clear acc]
A 8 D [load term]
R D [term/2]
[Common code, acc = new term]
[41] T 8 D [store new term]
A 7 F [load count]
A 54 @ [add 1]
T 7 F [update count]
E 12 @ [loop back]
[Here when sequence has reached 1
Assume jump here with acc = 0]
[46] E F [return with acc = 0]
[47] T F [here on error]
S 54 F [acc := -1]
T 7 F [return that as count]
E 46 @
[Arrange the following to ensure even addresses for 35-bit values]
[51] T 1024 F [for checking valid address]
[52] H 682 DT 682 D [(2^34 - 1)/3]
[54] P DP F [1]
[56] P 2 F [to change addresses by 2]
 
[Program to demonstrate Rosetta Code subroutine]
T 180 K
G K
[Double constants]
[P 500 F P F] [maximum n = 1000"]
[0] & 848 F PF [maximum n = 100000]
[2] P 13 D PF [n = 27 as demo of sequence]
[4] P D PF [1]
[Double variables]
[6] P F P F [n, start of Collatz sequence]
[8] P F P F [n with maximum count]
[Single constants]
[10] P 400 F [where to store sequence]
[11] P 2 F [to change addresses by 2]
[12] @ F [carriage return]
[13] & F [line feed]
[14] K 4096 F [null char]
[15] A D [used for maiking 'A addr D' order]
[16] P 8 F [ used for adding 8 to address]
[Single variables]
[17] P F [maximum number of terms]
[18] P F [temporary store]
[19] P F [marks end of printing]
 
[Subroutine to print 4 numbers starting at address in 6F.
Prints new line (CR, LF) at end.]
[20] A 3 F [plant link for return]
T 40 @
A 6 F [load start address]
A 15 @ [make 'A addr D' order]
A 16 @ [inc address by 8 (4 double values)]
U 19 @ [store as test for end]
S 16 @ [restore 'A addr D' order for start]
[27] U 31 @ [plant 'A addr D' order in code]
S 19 @ [test for end]
E 38 @ [out if so]
T F [clear acc]
[31] A D [load number]
T D [to 0D for printing]
[33] A 33 @ [call print subroutine]
G V
A 31 @ [load 'A addr D' order]
A 11 @ [inc address to next double value]
G 27 @ [loop back]
[38] O 12 @ [here when done, print CR LF]
O 13 @
[40] E F [return]
 
[Enter with acc = 0]
[PART 1]
[41] A 2#@ [load demo value of n]
T 4 D [to 4D for subroutine]
A 10 @ [address to store sequence]
T 6 F [to 6F for subroutine]
[45] A 45 @ [call subroutine to generate sequence]
G H
A 7 F [load length of sequence]
G 198 @ [out if error]
T 18 @
[Print result]
[50] A 50 @ [print 'start' message]
G C
K2048F SF TF AF RF TF !F !F #D
A 2#@ [load demo value of n]
T D [to 0D for printing]
[63] A 63 @ [print demo n]
G V
[65] A 65 @ [print 'length' string]
G C
K2048F @F &F LF EF NF GF TF HF !F #D
T D [ensure 1F and sandwich bit are 0]
A 18 @ [load length]
T F [to 0F (effectively 0D) for printing]
[81] A 81 @
G V
[83] A 83 @ [print 'first and last four' string]
G C
K2048F @F &F FF IF RF SF TF !F AF NF DF !F LF AF SF TF !F FF OF UF RF @F &F #D
A 18 @ [load length of sequence]
L 1 F [times 4]
A 6 F [make address of last 4]
S 16 @
T 18 @ [store address of last 4]
[115] A 115 @ [print first 4 terms]
G 20 @
A 18 @ [retrieve address of last 4]
T 6 F [pass as parameter]
[119] A 119 @ [print last 4 terms]
G 20 @
 
[PART 2]
T F
T 17 @ [max count := 0]
T 6#@ [n := 0]
[Loop: update n, start new sequence]
[124] T F [clear acc]
A 6#@ [load n]
A 4#@ [add 1 (double)]
U 6#@ [update n]
T 4 D [n to 4D for subroutine]
T 6 F [say no store]
[130] A 130 @ [call subroutine to generate sequence]
G H
A 7 F [load count returned by subroutine]
G 198 @ [out if error]
S 17 @ [compare with max count so far]
G 140 @ [skip if less]
A 17 @ [restore count after test]
T 17 @ [update max count]
A 6#@ [load n]
T 8#@ [remember n that gave max count]
[140] T F [clear acc]
A 6#@ [load n just done]
S #@ [compare with max(n)]
G 124 @ [loop back if n < max(n)
else fall through with acc = 0]
[Here whan reached maximum n. Print result.]
[144] A 144 @ [print 'max n' message]
G C
K2048F MF AF XF !F NF !F !F #D
A #@ [load maximum n]
T D [to 0D for printing]
[157] A 157 @ [call print subroutine]
G V
[159] A 159 @ [print 'max len' message]
G C
K2048F @F &F MF AF XF !F LF EF NF #D
T D [clear 1F and sandwich bit]
A 17 @ [load max count (single)]
T F [to 0F, effectively to 0D]
[175] A 175 @ [call print subroutine]
G V
[177] A 177 @ [print 'at n =' message]
G C
K2048F @F &F AF TF !F NF !F #F VF !D
A 8#@ [load n for which max count occurred]
T D [to 0D for printing]
[192] A 192 @ [call print subroutine]
G V
[194] O 12 @ [print CR, LF]
O 13 @
O 14 @ [print null to flush teleprinter buffer]
Z F [stop]
[Here if term would overflow EDSAC 35-bit value.
With a maximum n of 100,000 this doesn't happen.]
[198] A 198 @ [print 'overflow' message]
G C
K2048F @F &F OF VF EF RF FF LF OF WD
E 194 @ [jump to exit]
 
E 41 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
{{out}}
<pre>
START 27
LENGTH 112
FIRST AND LAST FOUR
27 82 41 124
8 4 2 1
MAX N 100000
MAX LEN 351
AT N = 77031
</pre>
 
=={{header|Egel}}==
<syntaxhighlight lang="egel">
import "prelude.eg"
 
namespace Hailstone (
 
using System
using List
 
def even = [ N -> (N%2) == 0 ]
 
def hailstone =
[ 1 -> {1}
| N -> if even N then cons N (hailstone (N/2))
else cons N (hailstone (N * 3 + 1)) ]
 
def hailpair =
[ N -> (N, length (hailstone N)) ]
 
def hailmax =
[ (N, NMAX), (M, MMAX) -> if (NMAX < MMAX) then (M, MMAX) else (N, NMAX) ]
 
def largest =
[ 1 -> (1, 1)
| N ->
let M0 = hailpair N in
let M1 = largest (N - 1) in
hailmax M0 M1 ]
)
 
using System
using List
using Hailstone
 
def task0 = let H27 = hailstone 27 in length H27
 
def task1 =
let H27 = hailstone 27 in
let L = length H27 in
(take 4 H27, drop (L - 4) H27)
 
def task2 = largest 100000
 
def main = (task0, task1, task2)
</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 2,474 ⟶ 4,000:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,481 ⟶ 4,007:
The last 4 elements are: 8 4 2 1
The longest sequence for numbers below 100000 is 351 for the number 77031.
</pre>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">import system'collections;
import extensions;
const int maxNumber = 100000;
Hailstone(int n,Map<int,int> lengths)
{
if (n == 1)
{
^ 1
};
while (true)
{
if (lengths.containsKey(n))
{
^ lengths[n]
}
else
{
if (n.isEven())
{
lengths[n] := 1 + Hailstone(n/2, lengths)
}
else
{
lengths[n] := 1 + Hailstone(3*n + 1, lengths)
}
}
}
}
public program()
{
int longestChain := 0;
int longestNumber := 0;
auto recursiveLengths := new Map<int,int>(4096,4096);
for(int i := 1; i < maxNumber; i+=1)
{
var chainLength := Hailstone(i, recursiveLengths);
if (longestChain < chainLength)
{
longestChain := chainLength;
longestNumber := i
}
};
console.printFormatted("max below {0}: {1} ({2} steps)", maxNumber, longestNumber, longestChain)
}</syntaxhighlight>
{{out}}
<pre>
max bellow 100000: 77031 (351 steps)
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Hailstone do
require Integer
Line 2,506 ⟶ 4,089:
end
 
Hailstone.run</langsyntaxhighlight>
 
{{out}}
Line 2,512 ⟶ 4,095:
Hailstone(27) has 112 elements: [27, 82, 41, 124, ..., 8, 4, 2, 1]
Longest sequence starting under 100000 begins with 77031 and has 351 elements.
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun hailstone = List by int n
List h = int[n]
while n != 1
n = when((n % 2 == 0), n / 2, 3 * n + 1)
h.append(n)
end
return h
end
int NUMBER = 27
int LESS_THAN = 100000
List sequence = hailstone(NUMBER)
writeLine("The hailstone sequence for the number " + NUMBER +
" has " + sequence.length + " elements")
writeLine("starting with " +
sequence.extractStart(4).join(", ") + " and ending with " +
sequence.extractEnd(4).join(", ") + ".")
int number = 0
sequence = int[]
for int i = 1; i < LESS_THAN; ++i
List current = hailstone(i)
if current.length > sequence.length
sequence = current
number = i
end
end
writeLine("The number less than 100000 with longest hailstone sequence is " +
number + ", with length of " + sequence.length + ".")
</syntaxhighlight>
{{out}}
<pre>
The hailstone sequence for the number 27 has 112 elements
starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1.
The number less than 100000 with longest hailstone sequence is 77031, with length of 351.
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(hailstone).
-import(io).
-export([main/0]).
Line 2,538 ⟶ 4,158:
io:format("finding maximum hailstone(N) length for 1 <= N <= 100000..."),
{Length, N} = max_length(1, 100000),
io:format(" done.~nhailstone(~B) length: ~B~n", [N, Length]).</langsyntaxhighlight>
{{out}}
<pre>Eshell V5.8.4 (abort with ^G)
Line 2,557 ⟶ 4,177:
This version has one collatz function for just calculating totals (just for fun) and the second generating lists.
 
<langsyntaxhighlight lang="erlang">
-module(collatz).
-export([main/0,collatz/1,coll/1,max_atz_under/1]).
Line 2,586 ⟶ 4,206:
io:format("Max: ~w~n", [max_atz_under(100000)]),
io:format("Total: ~w~n", [ length( Seq1000 ) ] ).
</syntaxhighlight>
</lang>
'''Output'''
<pre>
Line 2,602 ⟶ 4,222:
=={{header|ERRE}}==
In Italy it's known also as "Ulam conjecture".
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM ULAM
 
Line 2,633 ⟶ 4,253:
PRINT("Max. number is";NMAX;" with";MAX_COUNT;"elements")
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,665 ⟶ 4,285:
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function hailstone (n) ...
$ v=[n];
Line 2,710 ⟶ 4,330:
351
77031
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function hailstone(atom n)
sequence s
s = {n}
Line 2,758 ⟶ 4,378:
 
printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",
{imax,max})</langsyntaxhighlight>
{{out}}
<pre>hailstone(27) =
Line 2,779 ⟶ 4,399:
In cell '''A2''' enter this formula '''=IF(MOD(A1,2)=0,A1/2,A1*3+1)'''
Drag and copy the formula down until 4, 2, 1
 
=={{header|Ezhil}}==
Ezhil is a Tamil programming language, see [http://en.wikipedia.org/wiki/Ezhil_%28programming_language%29 | Wikipedia] entry.
 
<langsyntaxhighlight lang="src="Pythonpython"">
நிரல்பாகம் hailstone ( எண் )
பதிப்பி "=> ",எண் #hailstone seq
Line 2,803 ⟶ 4,424:
பதிப்பி "**********************************************"
முடி
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">let rec hailstone n = seq {
match n with
| 1 -> yield 1
| n when n % 2 = 0 -> yield n; yield! hailstone (n / 2)
| n -> yield n; yield! hailstone (n * 3 + 1)
}
 
let hailstone27 = hailstone 27 |> Array.ofSeq
assert (Array.length hailstone27 = 112)
assert (hailstone27.[..3] = [|27;82;41;124|])
assert (hailstone27.[108..] = [|8;4;2;1|])
 
let maxLen, maxI = Seq.max <| seq { for i in 1..99999 -> Seq.length (hailstone i), i}
printfn "Maximum length %d was found for hailstone(%d)" maxLen maxI</syntaxhighlight>
{{out}}
<pre>Maximum length 351 was found for hailstone(77031)</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone
Line 2,836 ⟶ 4,475:
PRIVATE>
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>$ ./factor -run=rosetta.hailstone
Line 2,847 ⟶ 4,486:
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[$1&$[%3*1+0~]?~[2/]?]n:
[[$." "$1>][n;!]#%]s:
[1\[$1>][\1+\n;!]#%]c:
Line 2,854 ⟶ 4,493:
0m:0f:
1[$100000\>][$c;!$m;>[m:$f:0]?%1+]#%
f;." has hailstone sequence length "m;.</langsyntaxhighlight>
 
=={{header|Fermat}}==
<syntaxhighlight lang="fermat">Array g[2]
 
Func Collatz(n, d) =
{Runs the Collatz procedure for the number n and returns the number of steps.}
{If d is nonzero, prints the terms in the sequence.}
steps := 1;
while n>1 do
if n|2=0 then n:=n/2 else n:=3n+1 fi;
if d then !!n fi;
steps := steps + 1
od;
steps.
 
Function LongestTo(n) =
{Finds the number up to n for which the Collatz algorithm takes the most number of steps.}
{The result is stored in the array [g]: g[1] is the number, g[2] is how many steps it takes.}
champ:=0;
record:=0;
for i = 1, n do
q:=Collatz(i, 0);
if q > record then
champ:=i; record:=q; fi;
od;
g[1]:=champ;
g[2]:=record;
.</syntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: hail-next ( n -- n )
dup 1 and if 3 * 1+ else 2/ then ;
: .hail ( n -- )
Line 2,875 ⟶ 4,542:
swap . ." has hailstone sequence length " . ;
 
100000 longest-hail</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Hailstone
implicit none
 
Line 2,927 ⟶ 4,594:
end subroutine
 
end program</langsyntaxhighlight>
{{out}}
<pre>
Line 2,940 ⟶ 4,607:
{{Works with|Frege|3.21.586-g026e8d7}}
 
<langsyntaxhighlight lang="frege">module Hailstone where
 
import Data.List (maximumBy)
Line 2,959 ⟶ 4,626:
let t4 = show $ drop (length h27 - 4) h27
putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4)
putStrLn $ show $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000]</langsyntaxhighlight>
 
{{out}}
Line 2,971 ⟶ 4,638:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
hailstone[n] :=
{
Line 3,002 ⟶ 4,669:
 
println["$longestN has length $longestLen"]
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<lang fsharp>let rec hailstone n = seq {
match n with
| 1 -> yield 1
| n when n % 2 = 0 -> yield n; yield! hailstone (n / 2)
| n -> yield n; yield! hailstone (n * 3 + 1)
}
 
let hailstone27 = hailstone 27 |> Array.ofSeq
assert (Array.length hailstone27 = 112)
assert (hailstone27.[..3] = [|27;82;41;124|])
assert (hailstone27.[108..] = [|8;4;2;1|])
 
let maxLen, maxI = Seq.max <| seq { for i in 1..99999 -> Seq.length (hailstone i), i}
printfn "Maximum length %d was found for hailstone(%d)" maxLen maxI</lang>
{{out}}
<pre>Maximum length 351 was found for hailstone(77031)</pre>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def
hailstone( 1 ) = [1]
hailstone( n ) = n # hailstone( if 2|n then n/2 else n*3 + 1 )
Line 3,033 ⟶ 4,682:
val (n, len) = maxBy( snd, [(i, hailstone( i ).length()) | i <- 1:100000] )
 
println( n, len )</langsyntaxhighlight>
 
{{out}}
Line 3,043 ⟶ 4,692:
=={{header|Futhark}}==
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun hailstone_step(x: int): int =
if (x % 2) == 0
Line 3,076 ⟶ 4,725:
(hailstone_seq x,
reduce max 0 (map hailstone_len (map (1+) (iota (n-1)))))
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn Hailstone( n as NSInteger ) as NSInteger
NSInteger count = 1
while ( n != 1 )
if ( n and 1 ) == 1
n = n * 3 + 1
count++
end if
n = n / 2
count++
wend
end fn = count
 
 
 
void local fn PrintHailstone( n as NSInteger )
NSInteger count = 1, col = 1
print "Sequence for number "; n; ":" : print
print using "########"; n;
col = 2
while ( n != 1 )
if ( n and 1 ) == 1
n = n * 3 + 1
count++
else
n = n / 2
count++
end if
print using "########"; n;
if col == 10 then print : col = 1 else col++
wend
print : print
print "Sequence length = "; count
end fn
 
window 1, @"Hailstone Sequence", ( 0, 0, 620, 400 )
 
NSInteger n, seq_num, x, max_x, max_seq
 
seq_num = 27
 
print
fn PrintHailstone( seq_num )
print
 
for x = 1 to 100000
n = fn Hailstone( x )
if n > max_seq
max_x = x
max_seq = n
end if
next
 
print "The longest sequence is for "; max_x; ", it has a sequence length of "; max_seq; "."
 
HandleEvents
</syntaxhighlight>
 
{{output}}
<pre>
Sequence for number 27:
 
27 82 41 124 62 31 94 47 142 71
214 107 322 161 484 242 121 364 182 91
274 137 412 206 103 310 155 466 233 700
350 175 526 263 790 395 1186 593 1780 890
445 1336 668 334 167 502 251 754 377 1132
566 283 850 425 1276 638 319 958 479 1438
719 2158 1079 3238 1619 4858 2429 7288 3644 1822
911 2734 1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325 976 488
244 122 61 184 92 46 23 70 35 106
53 160 80 40 20 10 5 16 8 4
2 1
 
Sequence length = 112
 
The longest sequence is for 77031, it has a sequence length of 351.
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Collatz_conjecture}}
 
'''Part 1.''' Create a routine to generate the hailstone sequence for a number
 
[[File:Fōrmulæ - Collatz conjecture 01.png]]
 
'''Part 2.''' Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with {27, 82, 41, 124} and ending with {8, 4, 2, 1}
 
[[File:Fōrmulæ - Collatz conjecture 02.png]]
 
[[File:Fōrmulæ - Collatz conjecture 03.png]]
 
[[File:Fōrmulæ - Collatz conjecture 04.png]]
 
[[File:Fōrmulæ - Collatz conjecture 05.png]]
 
'''Part 3.''' Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length
 
[[File:Fōrmulæ - Collatz conjecture 06.png]]
 
[[File:Fōrmulæ - Collatz conjecture 07.png]]
 
The sequence for the number 77,031 is the longest one, with 351 terms
 
[[File:Fōrmulæ - Collatz conjecture 08.png]]
 
[[File:Fōrmulæ - Collatz conjecture 09.png]]
 
'''Part 4.''' (Additional, not a requirement) Show the number less than 100,000 which has the highest value in its hailstone sequence together with that highest value
 
[[File:Fōrmulæ - Collatz conjecture 10.png]]
 
[[File:Fōrmulæ - Collatz conjecture 11.png]]
 
The sequence for the number 77,671 has the highest term: 1,570,824,736
 
[[File:Fōrmulæ - Collatz conjecture 12.png]]
 
[[File:Fōrmulæ - Collatz conjecture 13.png]]
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">CollatzSequence := function(n)
local v;
v := [ n ];
Line 3,138 ⟶ 4,914:
# [ 77031, 351 ]
CollatzMax(1, 1000000);
# [ 837799, 525 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,175 ⟶ 4,951:
}
fmt.Printf("hs(%d): %d elements\n", maxN, maxLen)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,189 ⟶ 4,965:
 
Output is the same as version above.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 3,256 ⟶ 5,032:
}
fmt.Printf("hs(%d): %d elements\n", nMaxLen, computedLen[nMaxLen])
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def hailstone = { long start ->
def sequence = []
while (start != 1) {
Line 3,266 ⟶ 5,042:
}
sequence << start
}</langsyntaxhighlight>
Test Code
<langsyntaxhighlight lang="groovy">def sequence = hailstone(27)
assert sequence.size() == 112
assert sequence[0..3] == [27, 82, 41, 124]
Line 3,274 ⟶ 5,050:
 
def results = (1..100000).collect { [n:it, size:hailstone(it).size()] }.max { it.size }
println results</langsyntaxhighlight>
{{out}}
<pre>[n:77031, size:351]</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (maximumBy)
import Data.Ord (comparing)
 
-------------------- HAILSTONE SEQUENCE ------------------
 
collatz :: Int -> Int
collatz n
| even n = n `div` 2
| otherwise = 1 + 3 * n
 
hailstone :: Int -> [Int]
hailstone = takeWhile (1 /= 1) . iterate collatz
where
collatz n =
if even n
then n `div` 2
else 3 * n + 1
 
longestChain :: Int
longestChain =
fst $
(maximumBy (comparing snd) (((,) <*> length . hailstone) <$> [1 .. 100000]))
(,) <*> (length . hailstone) <$> [1 .. 100000]
 
--TEST ------------------------------------------------ TEST -------------------------
main :: IO ()
main =
mapM_
putStrLn
[ "Collatz sequence for 27: ",
, (show . hailstone) 27,
, "The number " ++<> show longestChain,
, "has the longest hailstone sequence for any number less then 100000. ",
"for any number less then 100000. ",
, "The sequence has length: " ++ (show . length . hailstone $ longestChain)
"The sequence has length: "
]
<> (show . length . hailstone $ longestChain)
</lang>
]</syntaxhighlight>
{{out}}
{{Out}}
<pre>Collatz sequence for 27:
[27,82,41,124,62,31,94,47,142,71,214,107,322,161,484,242,121,364,182,91,274,137,412,206,103,310,155,466,233,700,350,175,526,263,790,395,1186,593,1780,890,445,1336,668,334,167,502,251,754,377,1132,566,283,850,425,1276,638,319,958,479,1438,719,2158,1079,3238,1619,4858,2429,7288,3644,1822,911,2734,1367,4102,2051,6154,3077,9232,4616,2308,1154,577,1732,866,433,1300,650,325,976,488,244,122,61,184,92,46,23,70,35,106,53,160,80,40,20,10,5,16,8,4,2]
Line 3,314 ⟶ 5,095:
 
The following is an older version, which some of the language examples on this page are translated from:
<langsyntaxhighlight lang="haskell">import Data.Ord (comparing)
import Data.List (maximumBy, intercalate)
 
Line 3,339 ⟶ 5,120:
maximumBy (comparing fst) $
withResult (length . hailstone) <$> [1 .. 100000]
]</langsyntaxhighlight>
{{out}}
<pre>112
Line 3,350 ⟶ 5,131:
One approach to using '''unfoldr''' and then '''foldr''' might be:
 
<syntaxhighlight lang ="haskell">import Data.List (unfoldr, intercalate)
 
 
-------------------- HAILSTONE SEQUENCE ------------------
 
hailStones :: Int -> [Int]
hailStones n = stones ++(<> [1]) . unfoldr go
where
stonesf =x
unfoldr| even x = div x 2
| otherwise (\x= ->1 + 3 * x
ifgo x < 2
| 2 > x then= Nothing
| otherwise = Just (x, f else Justx)
( x
, if even x
then div x 2
else (3 * x) + 1))
n
 
mostStones :: Int -> (Int, Int)
mostStones n = foldr go (0, 0) . enumFromTo 1
foldrwhere
(\go x (m, ml) ->
| l let> lml = length (hailStones x, l)
| otherwise in= if l >(m, ml)
then (x, l)where
l = elselength (m,hailStones ml)x)
(0, 0)
[1 .. n]
 
------------------------- GENERIC ------------------------
(len27, start27, end27) =
lastN_ :: Int -> [Int] -> [Int]
let xs = hailStones 27
lastN_ = (foldr (const (drop 1)) <*>) . drop
in (length xs, take 4 xs, reverse $ take 4 (reverse xs))
 
--------------------------- TEST -------------------------
h27, start27, end27 :: [Int]
[h27, start27, end27] = [id, take 4, lastN_ 4] <*> [hailStones 27]
 
maxNum, maxLen :: Int
(maxNum, maxLen) = mostStones 100000
 
report :: [String]
report =
[ "Sequence 27 length:"
, show len27
, "Sequence 27 start:"
, show start27
, "Sequence 27 end:"
, show end27
, ""
, "N with longest sequence where N <= 100000"
, show maxNum
, "length of this sequence:"
, show maxLen
]
 
main :: IO ()
main =
main = putStrLn $ intercalate "\n" report</lang>
mapM_
 
putStrLn
[ "Sequence 27 length:"
, show $ length h27
, "Sequence 27 start:"
, show start27
, "Sequence 27 end:"
, show end27
, ""
, "N with longest sequence where N <= 100000"
, show maxNum
, "length of this sequence:"
, show maxLen
]</syntaxhighlight>
{{Out}}
<pre>Sequence 27 length:
Line 3,416 ⟶ 5,196:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">DIMENSION stones(1000)
 
H27 = hailstone(27)
Line 3,449 ⟶ 5,229:
ENDIF
ENDDO
END</langsyntaxhighlight>
H27=112; first4(1)=27; first4(2)=82; first4(3)=41; first4(4)=124; ...; last4(1)=8; last4(2)=4; last4(3)=2; last4(4)=1;
<br /> number=77031; longest_sequence=351;
Line 3,455 ⟶ 5,235:
=={{header|Icon}} and {{header|Unicon}}==
A simple solution that <i>generates</i> (in the Icon sense) the sequence is:
<langsyntaxhighlight lang="icon">procedure hailstone(n)
while n > 1 do {
suspend n
Line 3,461 ⟶ 5,241:
}
suspend 1
end</langsyntaxhighlight>
and a test program for this solution is:
<langsyntaxhighlight lang="icon">procedure main(args)
n := integer(!args) | 27
every writes(" ",hailstone(n))
end</langsyntaxhighlight>
but this solution is computationally expensive when run repeatedly (task 3).
 
The following solution uses caching to improve performance on task 3 at the expense of space.
<langsyntaxhighlight lang="icon">procedure hailstone(n)
static cache
initial {
Line 3,478 ⟶ 5,258:
/cache[n] := [n] ||| hailstone(if n%2 = 0 then n/2 else 3*n+1)
return cache[n]
end</langsyntaxhighlight>
 
A test program is:
<langsyntaxhighlight lang="icon">procedure main(args)
n := integer(!args) | 27
task2(n)
Line 3,503 ⟶ 5,283:
}
write(maxN," has a sequence of ",maxHS," values")
end</langsyntaxhighlight>
A sample run is:
<pre>
Line 3,520 ⟶ 5,300:
->
</pre>
 
=={{header|Io}}==
Here is a simple, brute-force approach:
<lang io>
makeItHail := method(n,
stones := list(n)
while (n != 1,
if(n isEven,
n = n / 2,
n = 3 * n + 1
)
stones append(n)
)
stones
)
 
out := makeItHail(27)
writeln("For the sequence beginning at 27, the number of elements generated is ", out size, ".")
write("The first four elements generated are ")
for(i, 0, 3,
write(out at(i), " ")
)
writeln(".")
 
write("The last four elements generated are ")
for(i, out size - 4, out size - 1,
write(out at(i), " ")
)
writeln(".")
 
numOfElems := 0
nn := 3
for(x, 3, 100000,
out = makeItHail(x)
if(out size > numOfElems,
numOfElems = out size
nn = x
)
)
 
writeln("For numbers less than or equal to 100,000, ", nn,
" has the longest sequence of ", numOfElems, " elements.")
</lang>
 
{{out}}
<pre>
For the sequence beginning at 27, the number of elements generated is 112.
The first four elements generated are 27 82 41 124 .
The last four elements generated are 8 4 2 1 .
For numbers less than or equal to 100,000, 77031 has the longest sequence of 351 elements.
</pre>
 
=={{header|Ioke}}==
{{needs-review|Ioke|Calculates the Hailstone sequence but might not complete everything from task description.}}
<lang ioke>collatz = method(n,
n println
unless(n <= 1,
if(n even?, collatz(n / 2), collatz(n * 3 + 1)))
)</lang>
 
=={{header|Inform 7}}==
This solution uses a cache to speed up the length calculation for larger numbers.
{{works with|Glulx virtual machine}}
<langsyntaxhighlight lang="inform7">Home is a room.
 
To decide which list of numbers is the hailstone sequence for (N - number):
Line 3,635 ⟶ 5,356:
let best number be N;
say "The number under 100,000 with the longest hailstone sequence is [best number] with [best length] element[s].";
end the story.</langsyntaxhighlight>
 
{{out}}
<pre>Hailstone sequence for 27 has 112 elements: 27, 82, 41, 124 ... 8, 4, 2, 1.
The number under 100,000 with the longest hailstone sequence is 77031 with 351 elements.</pre>
 
=={{header|Io}}==
Here is a simple, brute-force approach:
<syntaxhighlight lang="io">
makeItHail := method(n,
stones := list(n)
while (n != 1,
if(n isEven,
n = n / 2,
n = 3 * n + 1
)
stones append(n)
)
stones
)
 
out := makeItHail(27)
writeln("For the sequence beginning at 27, the number of elements generated is ", out size, ".")
write("The first four elements generated are ")
for(i, 0, 3,
write(out at(i), " ")
)
writeln(".")
 
write("The last four elements generated are ")
for(i, out size - 4, out size - 1,
write(out at(i), " ")
)
writeln(".")
 
numOfElems := 0
nn := 3
for(x, 3, 100000,
out = makeItHail(x)
if(out size > numOfElems,
numOfElems = out size
nn = x
)
)
 
writeln("For numbers less than or equal to 100,000, ", nn,
" has the longest sequence of ", numOfElems, " elements.")
</syntaxhighlight>
 
{{out}}
<pre>
For the sequence beginning at 27, the number of elements generated is 112.
The first four elements generated are 27 82 41 124 .
The last four elements generated are 8 4 2 1 .
For numbers less than or equal to 100,000, 77031 has the longest sequence of 351 elements.
</pre>
 
=={{header|Ioke}}==
{{needs-review|Ioke|Calculates the Hailstone sequence but might not complete everything from task description.}}
<syntaxhighlight lang="ioke">collatz = method(n,
n println
unless(n <= 1,
if(n even?, collatz(n / 2), collatz(n * 3 + 1)))
)</syntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="j"> # hailseq 27 NB. sequence length
112
4 _4 {."0 1 hailseq 27 NB. first & last 4 numbers in sequence
Line 3,651 ⟶ 5,431:
8 4 2 1
(>:@(i. >./) , >./) #@hailseq }.i. 1e5 NB. number < 100000 with max seq length & its seq length
77031 351</langsyntaxhighlight>
See also the [[j:Essays/Collatz Conjecture|Collatz Conjecture essay on the J wiki]].
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Line 3,751 ⟶ 5,531:
return;
}
}</langsyntaxhighlight>
{{out}}
<pre>Sequence for 27 has 112 elements: [27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Line 3,762 ⟶ 5,542:
===ES5===
====Imperative====
<langsyntaxhighlight lang="javascript">function hailstone (n) {
var seq = [n];
while (n > 1) {
Line 3,784 ⟶ 5,564:
}
}
print("longest sequence: " + max + " numbers for starting point " + n);</langsyntaxhighlight>
{{out}}
<pre>sequence 27 is (27, 82, 41, 124 ... 8, 4, 2, 1). length: 112
Line 3,797 ⟶ 5,577:
(translating one of the Haskell solutions).
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// Hailstone Sequence
Line 3,816 ⟶ 5,596:
};
 
})();</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">{"length":112,"sequence":[27,82,41,124,62,31,94,47,142,71,214,
107,322,161,484,242,121,364,182,91,274,137,412,206,103,310,155,466,233,700,350,
175,526, 263,790,395,1186,593,1780,890,445,1336,668,334,167,502,251,754,377,
Line 3,826 ⟶ 5,606:
2429,7288,3644,1822,911,2734,1367,4102,2051,6154,3077,9232,4616,2308,1154,577,
1732,866,433,1300,650,325,976,488,244,122,61,184,92,46,23,70,35,106,53,160,80,
40,20,10,5,16,8,4,2,1]}</langsyntaxhighlight>
 
Attempting to fold that recursive function over an array of 100,000 elements,
Line 3,832 ⟶ 5,612:
space, at least on the system used here.
 
The stack problem can be quickly fixed, as often, by simply applying a generic '''memoized()''' function ,
to derive a version of '''hailstone()''', which reuses previously calculated paths.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
function memoizedmemoizedHailstone(fn) {
var dctMemo = {};
 
return function hailstone(xn) {
var varValuevalue = dctMemo[xn];
 
if ('u'typeof value === (typeof varValue)[0]"undefined") {
dctMemo[xn] = varValuevalue = fn(xn === 1); ?
[1] : ([n].concat(hailstone(n % 2 ? n * 3 + 1 : n / 2)));
return varValue;
};
return value;
}
}
 
// Hailstone Sequence
// Derived a memoized version of the function,
// n -> [n]
// which can reuse previously calculated paths
function hailstone(n) {
var fnCollatz = memoizedHailstone();
return n === 1 ? [1] : (
[n].concat(
hailstone(n % 2 ? n * 3 + 1 : n / 2)
)
)
}
// Derived a memoized version of the function,
// which can reuse previously calculated paths
var fnCollatz = memoized(hailstone);
 
// Iterative version of range
Line 3,892 ⟶ 5,664:
return longestBelow(100000);
 
})();</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">// Number, length of sequence
{"n":77031, "l":351}</langsyntaxhighlight>
 
For better time (as well as space) we can continue to memoize while falling back to a function which returns the
Line 3,904 ⟶ 5,676:
for integers below one million, or ten million and beyond, without hitting the limits of system resources.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (n) {
 
var dctMemo = {};
Line 3,956 ⟶ 5,728:
return [100000, 1000000, 10000000].map(longestBelow);
 
})();</langsyntaxhighlight>
 
{{out}}
 
<syntaxhighlight lang="javascript">[
<lang JavaScript>[
{"n":77031, "l":351}, // 100,000
{"n":837799, "l":525}, // 1,000,000
{"n":8400511, "l":686} // 10,000,000
]</langsyntaxhighlight>
 
<langsyntaxhighlight JavaScriptlang="javascript">longestBelow(100000000)
-> {"n":63728127, "l":950}</langsyntaxhighlight>
 
===ES6===
<syntaxhighlight lang="javascript">(() => {
 
// hailstones :: Int -> [Int]
Longest sequence for an integer under N:
const hailstones = x => {
<lang javascript>(() => {
const dctMemocollatz = {};memoized(n =>
even(n) ? div(n, 2) : (3 * n) + 1);
return reverse(until(
xs => xs[0] === 1,
xs => cons(collatz(xs[0]), xs), [x]
));
};
 
// Length only of hailstone sequence
// collatzLength :: Int -> Int
const collatzLength = n => {
let i = 1;until(
let a xi => xi[0] === n;1,
([x, i]) => [(x % 2 ? 3 * x + 1 : x / 2), i + 1], //
let lng;
[n, 1]
)[1];
 
// GENERIC FUNCTIONS -----------------------------------------------------
while (a !== 1) {
 
lng = dctMemo[a];
// comparing :: (a -> b) -> (a if-> ('u'a ===-> (typeof lngOrdering)[0]) {
const comparing = f =>
a = (a % 2 ? 3 * a + 1 : a / 2);
(x, y) => i++;{
} else return lng + i - 1;const
} a = f(x),
return i b = f(y);
return a < b ? -1 : (a > b ? 1 : 0);
};
};
 
// cons :: a -> [a] -> [a]
const cons = (x, xs) => [x].concat(xs);
 
// div :: Int -> Int -> Int
const div = (x, y) => Math.floor(x / y);
 
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
 
// even :: Int -> Bool
const even = n => n % 2 === 0;
 
// fst :: (a, b) -> a
const fst = pair => pair.length === 2 ? pair[0] : undefined;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// rangemaximumBy :: Int(a -> Inta -> Maybe IntOrdering) -> [Inta] -> a
const rangemaximumBy = (mf, n, deltaxs) => {
constxs.length blnUp> =0 n >? m,(
d = blnUp ? xs.slice(delta || 1) : -(delta || 1),
lng = Math.absreduce(Math.floor((blnUpa, ?x) n=> -f(x, ma) :> m0 -? n)x /: d)a, + 1xs[0]),
) : a = Array(lng)undefined;
let i = lng;
 
// memoized :: (a while-> (i--b) a[i] =-> (da *-> ib) + m;
const memoized = f return=> a;{
const dctMemo = {};
return x => {
const v = dctMemo[x];
return v !== undefined ? v : (dctMemo[x] = f(x));
};
};
 
// longestBelowreverse :: Int[a] -> {Number::Int, Length:Int}[a]
const longestBelowreverse = nxs =>
rangexs.slice(1, n0)
.reducereverse();
(a, x) => {
const lng = dctMemo[x] || (dctMemo[x] = collatzLength(x));
 
// unlines :: [String] -> String
return lng > a.l ? {
const unlines = xs => xs.join('\n: x,');
l: lng
} : a
 
// until :: (a -> Bool) -> (a },-> {a) -> a -> a
const until = (p, f, x) => n: 0,{
let v = l: 0x;
while (!p(v)) v = }f(v);
)return v;
};
 
// MAIN ------------------------------------------------------------------
// TEST
const
// show :: a -> String
const show = x =>// JSON.stringify(x,ceiling null,:: 2);Int
ceiling = 100000,
 
// (maxLen, maxNum) :: (Int, Int)
return show(
[100000maxLen, 1000000,maxNum] 10000000].map(longestBelow)=
); maximumBy(
comparing(fst),
})();</lang>
map(i => [collatzLength(i), i], enumFromTo(1, ceiling))
);
return unlines([
'Collatz sequence for 27: ',
`${hailstones(27)}`,
'',
`The number ${maxNum} has the longest hailstone sequence`,
`for any starting number under ${ceiling}.`,
'',
`The length of that sequence is ${maxLen}.`
]);
})();</syntaxhighlight>
{{Out}}
(Run in the Atom editor, through the Script package)
<pre>Collatz sequence for 27:
<pre>[
27,82,41,124,62,31,94,47,142,71,214,107,322,161,484,242,121,364,182,91,
{
274,137,412,206,103,310,155,466,233,700,350,175,526,263,790,395,1186,593,
"n": 77031,
1780,890,445,1336,668,334,167,502,251,754,377,1132,566,283,850,425,1276,
"l": 351
638,319,958,479,1438,719,2158,1079,3238,1619,4858,2429,7288,3644,1822,
},
911,2734,1367,4102,2051,6154,3077,9232,4616,2308,1154,577,1732,866,433,
{
1300,650,325,976,488,244,122,61,184,92,46,23,70,35,106,53,160,80,40,20,
"n": 837799,
10,5,16,8,4,2,1
"l": 525
 
},
The number 77031 has the longest hailstone sequence
{
for any starting number under 100000.
"n": 8400511,
 
"l": 686
The length of that sequence is 351.
}
 
]
[Finished in 21.897s139s]</pre>
</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># Generate the hailstone sequence as a stream to save space (and time) when counting
def hailstone:
recurse( if . > 1 then
Line 4,065 ⟶ 5,882:
([0,0];
($i | count(hailstone)) as $l
| if $l > .[1] then [$i, $l] else . end);</langsyntaxhighlight>
'''Examples''':
<langsyntaxhighlight lang="jq">[27|hailstone] as $h
| "[27|hailstone]|length is \($h|length)",
"The first four numbers: \($h[0:4])",
Line 4,073 ⟶ 5,890:
"",
max_hailstone(100000) as $m
| "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))"</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -M -r -n -f hailstone.jq
[27|hailstone]|length is 112
The first four numbers: [27,82,41,124]
The last four numbers: [8,4,2,1]
 
Maximum length for n|hailstone for n in 1..100000 is 351 (n == 77031)</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6 and 1.0+}}
<lang julia>function hailstone(n)
 
seq = [n]
===Dynamic solution===
while n>1
<syntaxhighlight lang="julia">function hailstonelength(n::Integer)
n = n % 2 == 0 ? n >> 1 : 3n + 1
len = 1
push!(seq,n)
while n > 1
n = ifelse(iseven(n), n ÷ 2, 3n + 1)
len += 1
end
return len
end
 
@show hailstonelength(27); nothing
@show findmax([hailstonelength(i) for i in 1:100_000]); nothing</syntaxhighlight>
 
{{out}}
<pre>
hailstonelength(27) = 112
findmax((hailstonelength(i) for i = 1:100000)) = (351, 77031)
</pre>
 
===Solution with iterator===
====Julia 1.0====
{{works with|Julia|1.0+}}
<syntaxhighlight lang="julia">struct HailstoneSeq{T<:Integer}
count::T
end
 
Base.eltype(::HailstoneSeq{T}) where T = T
 
function Base.iterate(h::HailstoneSeq, state=h.count)
if state == 1
(1, 0)
elseif state < 1
nothing
elseif iseven(state)
(state, state ÷ 2)
elseif isodd(state)
(state, 3state + 1)
end
end
 
function Base.length(h::HailstoneSeq)
len = 0
for _ in h
len += 1
end
return len
end
 
function Base.show(io::IO, h::HailstoneSeq)
f5 = collect(Iterators.take(h, 5))
print(io, "HailstoneSeq{", join(f5, ", "), "...}")
end
 
hs = HailstoneSeq(27)
println("Collection of the Hailstone sequence from 27: $hs")
cl = collect(hs)
println("First 5 elements: ", join(cl[1:5], ", "))
println("Last 5 elements: ", join(cl[end-4:end], ", "))
Base.isless(h::HailstoneSeq, s::HailstoneSeq) = length(h) < length(s)
println("The number with the longest sequence under 100,000 is: ", maximum(HailstoneSeq.(1:100_000)))</syntaxhighlight>
 
{{out}}
<pre>Collection of the Hailstone sequence from 27: HailstoneSeq{27, 82, 411, 124, 62...}
First 5 elements: 27, 82, 41, 124, 62
Last 5 elements: 16, 8, 4, 2, 1
The number with the longest sequence under 100,000 is: HailstoneSeq{777031, 231094, 115547, 346642, 173321...}</pre>
 
====Julia 0.6====
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">struct HailstoneSeq{T<:Integer}
start::T
end
 
Base.eltype(::HailstoneSeq{T}) where T = T
 
Base.start(hs::HailstoneSeq) = (-1, hs.start)
Base.done(::HailstoneSeq, state) = state == (1, 4)
function Base.next(::HailstoneSeq, state)
_, s2 = state
s1 = s2
if iseven(s2)
s2 = s2 ÷ 2
else
s2 = 3s2 + 1
end
return seqs1, (s1, s2)
end</lang>
<pre>julia> h = hailstone(27);
 
function Base.length(hs::HailstoneSeq)
julia> @assert length(h) == 112
r = 0
for _ in hs
r += 1
end
return r
end
 
function Base.show(io::IO, hs::HailstoneSeq)
julia> @assert h[1:4] == [27,82,41,124]
f5 = collect(Iterators.take(hs, 5))
print(io, "HailstoneSeq(", join(f5, ", "), "...)")
end
 
hs = HailstoneSeq(27)
julia> @assert h[end-3:end] == [8,4,2,1]
println("Collection of the Hailstone sequence from 27: $hs")
cl = collect(hs)
println("First 5 elements: ", join(cl[1:5], ", "))
println("Last 5 elements: ", join(cl[end-4:end], ", "))
 
Base.isless(h::HailstoneSeq, s::HailstoneSeq) = length(h) < length(s)
julia> maximum([(length(hailstone(i)),i) for i in 1:100000])
println("The number with the longest sequence under 100,000 is: ", maximum(HailstoneSeq.(1:100_000)))</syntaxhighlight>
(351,77031)</pre>
 
{{out}}
<pre>Collection of the Hailstone sequence from 27: HailstoneSeq(27, 82, 41, 124, 62...)
First 5 elements: 27, 82, 41, 124, 62
Last 5 elements: 16, 8, 4, 2, 1
The number with the longest sequence under 100,000 is: HailstoneSeq(77031, 231094, 115547, 346642, 173321...)</pre>
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> hail: (1<){:[x!2;1+3*x;_ x%2]}\
seqn: hail 27
 
Line 4,114 ⟶ 6,032:
 
{m,x@s?m:|/s:{#hail x}'x}{x@&x!2}!:1e5
351 77031</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang ="kotlin">import java.util.ArrayDeque
fun hailstone(start: Int) = generateSequence(start) { n ->
when {
n == 1 -> null
n % 2 == 0 -> n / 2
else -> n * 3 + 1
}
}
 
fun main() {
val hail27 = hailstone(27).toList()
println("The hailstone sequence for 27 has ${hail27.size} elements:\n$hail27")
 
val (n, length) = (1..100000).asSequence()
.map { it to hailstone(it).count() }
.maxBy { it.second }
println("The number between 1 and 100000 with the longest hailstone sequence is $n, of length $length")
}
</syntaxhighlight>
 
 
Alternative, doing it manually:
 
<syntaxhighlight lang="kotlin">import java.util.ArrayDeque
 
fun hailstone(n: Int): ArrayDeque<Int> {
Line 4,140 ⟶ 6,081:
println("${longestHail.first} is the number less than 100000 with " +
"the longest sequence, having length ${longestHail.size}.")
}</langsyntaxhighlight>
 
{{out}}
Line 4,147 ⟶ 6,088:
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">[
<lang Lasso>[
define_tag("hailstone", -required="n", -type="integer", -copy);
local("sequence") = array(#n);
Line 4,178 ⟶ 6,119:
"<br/>";
"Number with the longest sequence under 100,000: " #longest_index + ", with " + #longest_sequence + " elements.";
]</langsyntaxhighlight>
 
=={{header|Logo}}==
<lang logo>to hail.next :n
output ifelse equal? 0 modulo :n 2 [:n/2] [3*:n + 1]
end
 
to hail.seq :n
if :n = 1 [output [1]]
output fput :n hail.seq hail.next :n
end
 
show hail.seq 27
show count hail.seq 27
 
to max.hail :n
localmake "max.n 0
localmake "max.length 0
repeat :n [if greater? count hail.seq repcount :max.length [
make "max.n repcount
make "max.length count hail.seq repcount
] ]
(print :max.n [has hailstone sequence length] :max.length)
end
 
max.hail 100000</lang>
 
=={{header|Limbo}}==
 
<syntaxhighlight lang="text">implement Hailstone;
 
include "sys.m"; sys: Sys;
Line 4,259 ⟶ 6,175:
return i :: hailstone((big 3 * i) + big 1);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,267 ⟶ 6,183:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on hailstone (n, sequenceList)
len = 1
repeat while n<>1
Line 4,280 ⟶ 6,196:
if listP(sequenceList) then sequenceList.add(n)
return len
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="lingo">sequenceList = []
hailstone(27, sequenceList)
put sequenceList
Line 4,297 ⟶ 6,213:
end repeat
put n, maxLen
-- 77031 351</langsyntaxhighlight>
 
=={{header|Logo}}==
<syntaxhighlight lang="logo">to hail.next :n
output ifelse equal? 0 modulo :n 2 [:n/2] [3*:n + 1]
end
 
to hail.seq :n
if :n = 1 [output [1]]
output fput :n hail.seq hail.next :n
end
 
show hail.seq 27
show count hail.seq 27
 
to max.hail :n
localmake "max.n 0
localmake "max.length 0
repeat :n [if greater? count hail.seq repcount :max.length [
make "max.n repcount
make "max.length count hail.seq repcount
] ]
(print :max.n [has hailstone sequence length] :max.length)
end
 
max.hail 100000</syntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">:- object(hailstone).
 
:- public(generate_sequence/2).
Line 4,393 ⟶ 6,334:
).
 
:- end_object.</langsyntaxhighlight>
Testing:
<langsyntaxhighlight lang="logtalk">| ?- hailstone::write_sequence(27).
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
true
Line 4,405 ⟶ 6,346:
| ?- hailstone::longest_sequence(1, 100000, N, Length).
N = 77031, Length = 351
true</langsyntaxhighlight>
 
=={{header|LOLCODE}}==
There is presently no way to query a <tt>BUKKIT</tt> for the existence of a given key, thus making memoization infeasible. This solution takes advantage of prior knowledge to run in reasonable time.
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
HOW IZ I hailin YR stone
Line 4,457 ⟶ 6,398:
VISIBLE "len(hail(" max ")) = " len
 
KTHXBYE</langsyntaxhighlight>
{{out}}
<pre>hail(27) = 27 82 41 124 ... 8 4 2 1, length = 112
Line 4,463 ⟶ 6,404:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function hailstone( n, print_numbers )
local n_iter = 1
 
Line 4,492 ⟶ 6,433:
end
 
print( string.format( "Needed %d iterations for the number %d.\n", max_iter, max_i ) )</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Use of two versions of Hailstone, one which return each n, and another one which return only the length of sequence.
 
Also we use current stack as FIFO to get the last 4 numbers
<syntaxhighlight lang="m2000 interpreter">
Module hailstone.Task {
hailstone=lambda (n as long)->{
=lambda n (&val) ->{
if n=1 then =false: exit
=true
if n mod 2=0 then n/=2 : val=n: exit
n*=3 : n++: val=n
}
}
Count=Lambda (n) ->{
m=lambda n ->{
if n=1 then =false: exit
=true :if n mod 2=0 then n/=2 :exit
n*=3 : n++
}
c=1
While m() {c++}
=c
}
k=Hailstone(27)
counter=1
x=0
Print 27,
While k(&x) {
counter++
Print x,
if counter=4 then exit
}
Print
Flush ' empty current stack
While k(&x) {
counter++
data x ' send to end of stack -used as FIFO
if stack.size>4 then drop
}
\\ [] return a stack object and leave empty current stack
\\ Print use automatic iterator to print all values in columns.
Print []
Print "counter:";counter
m=0
For i=2 to 99999 {
m1=max.data(count(i), m)
if m1<>m then m=m1: im=i
}
Print Format$("Number {0} has then longest hailstone sequence of length {1}", im, m)
}
hailstone.Task
</syntaxhighlight>
{{out}}
<pre>
27 82 41 124
8 4 2 1
counter:112
Number 77031 has then longest hailstone sequence of length 351
</pre >
 
=={{header|Maple}}==
Define the procedure:
<syntaxhighlight lang="maple">
<lang Maple>
hailstone := proc( N )
local n := N, HS := Array([n]);
Line 4,509 ⟶ 6,512:
HS;
end proc;
</syntaxhighlight>
</lang>
Run the command and show the appropriate portion of the result;
<syntaxhighlight lang="maple">
<lang Maple>
> r := hailstone(27):
[ 1..112 1-D Array ]
Line 4,519 ⟶ 6,522:
> r(1..4) ... r(-4..);
[27, 82, 41, 124] .. [8, 4, 2, 1]
</syntaxhighlight>
</lang>
Compute the first 100000 sequences:
<syntaxhighlight lang="maple">
<lang Maple>
longest := 0; n := 0;
for i from 1 to 100000 do
Line 4,531 ⟶ 6,534:
od:
printf("The longest Hailstone sequence in the first 100k is n=%d, with %d terms\n",n,longest);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,541 ⟶ 6,544:
 
=== Nested function call formulation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneF[n_] := NestWhileList[If[OddQ@[#], 3 # + 1, #/2] &, n, # > 1 &]</langsyntaxhighlight>
 
This is probably the most readable and shortest implementation.
 
=== Fixed-Point formulation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneFP[n_] := Most@FixedPointList[Switch[#, 1, 1, _?OddQ , 3# + 1, _, #/2] &, n]</langsyntaxhighlight>
 
=== Recursive formulation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneR[1] = {1}
HailstoneR[n_?OddQ] := Prepend[HailstoneR[3 n + 1], n]
HailstoneR[n_] := Prepend[HailstoneR[n/2], n] </langsyntaxhighlight>
 
=== Procedural implementation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneP[n_] := Module[{x = {n}, s = n},
While[s > 1, x = {x, s = If[OddQ@s, 3 s + 1, s/2]}]; Flatten@x] </langsyntaxhighlight>
 
=== Validation ===
 
I use this version to do the validation:
<langsyntaxhighlight Mathematicalang="mathematica">Hailstone[n_] :=
NestWhileList[WhichIf[Mod[#, 2] == 0, #/2, True, ( 3*# + 1) ] &, n, # != 1 &];
 
 
Line 4,573 ⟶ 6,576:
{i, 100000}
]
Print["Longest Hailstone sequence at n = ", longest, "\nwith length = ", comp]; </langsyntaxhighlight>
{{out}}
<pre>
Line 4,584 ⟶ 6,587:
 
==== Sequence 27 ====
<langsyntaxhighlight Mathematicalang="mathematica">With[{seq = HailstoneFP[27]}, { Length[seq], Take[seq, 4], Take[seq, -4]}]</langsyntaxhighlight>
{{out}}
<pre>{112, {27, 82, 41, 124}, {8, 4, 2, 1}}</pre>
 
Alternatively,
<syntaxhighlight lang Mathematica="mathematica">Short[HailstoneFP[27],0.45]</langsyntaxhighlight>
 
{{out}}
Line 4,595 ⟶ 6,598:
 
==== Longest sequence length ====
<langsyntaxhighlight Mathematicalang="mathematica">MaximalBy[Table[{i, Length[HailstoneFP[i]]}, {i, 100000}], Last]</langsyntaxhighlight>
{{out}}
<pre>{{77031, 351}}</pre>
Line 4,601 ⟶ 6,604:
=={{header|MATLAB}} / {{header|Octave}}==
===Hailstone Sequence For N===
<langsyntaxhighlight Matlablang="matlab">function x = hailstone(n)
x = n;
while n > 1
Line 4,611 ⟶ 6,614:
end
x(end + 1) = n; %#ok
end</langsyntaxhighlight>
Show sequence of hailstone(27) and number of elements:
<langsyntaxhighlight Matlablang="matlab">x = hailstone(27);
fprintf('hailstone(27): %d %d %d %d ... %d %d %d %d\nnumber of elements: %d\n', x(1:4), x(end-3:end), numel(x))</langsyntaxhighlight>
{{out}}
<pre>hailstone(27): 27 82 41 124 ... 8 4 2 1
Line 4,621 ⟶ 6,624:
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length:
====Basic Version (use the above routine)====
<langsyntaxhighlight Matlablang="matlab">N = 1e5;
maxLen = 0;
for k = 1:N
Line 4,629 ⟶ 6,632:
n = k;
end
end</langsyntaxhighlight>
{{out}}
<pre>n = 77031
maxLen = 351</pre>
====Faster Version====
<langsyntaxhighlight lang="matlab">function [n, maxLen] = longestHailstone(N)
maxLen = 0;
for k = 1:N
Line 4,651 ⟶ 6,654:
n = k;
end
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="matlab">>> [n, maxLen] = longestHailstone(1e5)
n = 77031
maxLen = 351</langsyntaxhighlight>
====Much Faster Version With Caching====
<langsyntaxhighlight lang="matlab">function [n, maxLen] = longestHailstone(N)
lenList(N) = 0;
lenList(1) = 1;
Line 4,678 ⟶ 6,681:
n = k;
end
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="matlab">>> [n, maxLen] = longestHailstone(1e5)
n = 77031
maxLen = 351</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">collatz(n) := block([L], L: [n], while n > 1 do
(n: if evenp(n) then n/2 else 3*n + 1, L: endcons(n, L)), L)$
 
Line 4,699 ⟶ 6,702:
length(%); /* 112 */
collatz_length(27); /* 112 */
collatz_max(100000); /* [77031, 351] */</langsyntaxhighlight>
 
=={{header|Mercury}}==
The actual calculation (including module ceremony)
providing both a function and a predicate implementation:
<langsyntaxhighlight lang="mercury">:- module hailstone.
 
:- interface.
Line 4,722 ⟶ 6,725:
; hailstone(3 * N + 1, S) ).
 
:- end_module hailstone.</langsyntaxhighlight>
 
The mainline test driver (making use of [http://en.wikipedia.org/wiki/Unification_(computer_science) unification] for more succinct tests):
<langsyntaxhighlight lang="mercury">:- module test_hailstone.
 
:- interface.
Line 4,760 ⟶ 6,763:
; io.write_string("At least one test failed.\n", !IO) ).
 
:- end_module test_hailstone.</langsyntaxhighlight>
 
{{out}} of running this program is:
Line 4,767 ⟶ 6,770:
For those unused to logic programming languages it seems that nothing has been proved in terms of confirming anything, but if you look at the predicate declaration for <code>longest/3</code> …
 
<langsyntaxhighlight lang="mercury">:- pred longest(int::in, int::out, int::out) is det.</langsyntaxhighlight>
 
… you see that the second and third parameters are '''output''' parameters.
Line 4,777 ⟶ 6,780:
Thus we know that the correct sequences and values were generated
without bothering to print them out.
 
=={{header|MiniScript}}==
===Non-cached version===
Calculates sequence without using previous calculated sequences.
 
<syntaxhighlight lang="miniscript">
getSequence = function(n)
results = [n]
while n > 1
if n % 2 then
n = 3 * n + 1
else
n = n / 2
end if
results.push n
end while
return results
end function
 
h = getSequence(27)
print "The hailstone sequence for 27 has 112 elements starting with"
print h[:4]
print "and ending with"
print h[-4:]
 
maxSeqLen = 0
maxSeqVal = 0
for i in range(1,100000)
h = getSequence(i)
if h.len > maxSeqLen then
maxSeqLen = h.len
maxSeqVal = i
end if
end for
print
print "The number < 100,000 which has the longest hailstone sequence is " + maxSeqVal + "."
print "This sequence has " + maxSeqLen + " elements."
</syntaxhighlight>
{{out}}
<pre>The hailstone sequence for 27 has 112 elements starting with
[27, 82, 41, 124]
and ending with
[8, 4, 2, 1]
 
The number < 100,000 which has the longest hailstone sequence is 77031.
This sequence has 351 elements.</pre>
 
===Cached version===
Calculations are stored for used in later calculations.
<syntaxhighlight lang="miniscript">
cache = {}
calc = function(n)
if cache.hasIndex(n) then return
items = [n]
origNum = n
while n > 1 and not cache.hasIndex(n)
if n % 2 then
n = 3 * n + 1
else
n = n /2
end if
items.push n
end while
cache[origNum] = {"len": items.len,"items":items}
end function
 
getLen = function(n)
if not cache.hasIndex(n) then calc n
if n == 1 then return 1
return cache[n].len + getLen(cache[n].items[-1]) - 1
end function
 
getSequence = function(n)
if not cache.hasIndex(n) then calc n
if n == 1 then return [1]
return cache[n].items[:-1] + getSequence(cache[n].items[-1])
end function
 
h = getSequence(27)
print "The hailstone sequence for 27 has " + h.len + " elements starting with"
print h[:4]
print "and ending with"
print h[-4:]
 
longSeq = 0
longSeqVal =0
for i in range(2, 100000)
seq = getLen(i)
if longSeq < seq then
longSeq = seq
longSeqVal = i
end if
end for
print "The number < 100,000 which has the longest hailstone sequence is " + longSeqVal + "."
print "This sequence has " + longSeq + " elements."
</syntaxhighlight>
 
{{out}}Output is the same as the non-cached version above.
<pre>The hailstone sequence for 27 has 112 elements starting with
[27, 82, 41, 124]
and ending with
[8, 4, 2, 1]
 
The number < 100,000 which has the longest hailstone sequence is 77031.
This sequence has 351 elements.</pre>
 
=={{header|ML}}==
==={{header|MLite}}===
<langsyntaxhighlight lang="ocaml">fun hail (x = 1) = [1]
| (x rem 2 = 0) = x :: hail (x div 2)
| x = x :: hail (x * 3 + 1)
Line 4,814 ⟶ 6,922:
print ` ref (biggest, 0);
print " and is of length ";
println ` ref (biggest, 1);</langsyntaxhighlight>
{{out}}
<pre>hailstone sequence for the number 27 has 112 elements starting with [27, 82, 41, 124] and ending with [8, 4, 2, 1].
Line 4,820 ⟶ 6,928:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE hailst;
 
IMPORT InOut;
Line 4,892 ⟶ 7,000:
FindMax (100000);
InOut.WriteString ("Done."); InOut.WriteLn
END hailst.</langsyntaxhighlight>
Producing:
<pre>jan@Beryllium:~/modula/rosetta$ hailst
Line 4,920 ⟶ 7,028:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">hailstone(n) ;
If n=1 Quit n
If n#2 Quit n_" "_$$hailstone(3*n+1)
Quit n_" "_$$hailstone(n\2)
Set x=$$hailstone(27) Write !,$Length(x," ")," terms in ",x,!
112 terms in 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def hailstone(n)
seq = list()
while (n > 1)
append seq n
if (n % 2)=0
n = int(n / 2)
else
n = int((3 * n) + 1)
end
end
append seq n
return seq
end
h = hailstone(27)
println "hailstone(27)"
println "total elements: " + len(hailstone(27))
print h[0] + ", " + h[1] + ", " + h[2] + ", " + h[3] + ", ..., "
println h[-4] + ", " + h[-3] + ", " + h[-2] + ", " + h[-1]
max = 0
maxLoc = 0
for i in range(1,99999)
result = len(hailstone(i))
if (result > max)
max = result
maxLoc = i
end
end
print "\nThe number less than 100,000 with the longest sequence is "
println maxLoc + " with a length of " + max</syntaxhighlight>
{{out}}
<pre>hailstone(27)
total elements: 112
27, 82, 41, 124, ..., 8, 4, 2, 1
 
The number less than 100,000 with the longest sequence is 77031 with a length of 351</pre>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
Line 4,971 ⟶ 7,119:
hs = hs' 'hn
 
return hs.strip</langsyntaxhighlight>
{{out}}
<pre>
Line 4,981 ⟶ 7,129:
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc hailstone(n: int): seq[int] =
{{trans|Python}}
<lang nim>proc hailstone(n): auto =
result = @[n]
var n = n
Line 4,992 ⟶ 7,139:
result.add n
 
 
let h = hailstone 27
when isMainModule:
assert h.len == 112 and h[0..3] == @[27,82,41,124] and h[h.high-3..h.high] == @[8,4,2,1]
import strformat, strutils
var m, mi = 0
let h = hailstone(27)
for i in 1 .. <100_000:
echo &"Hailstone sequence for number 27 has {h.len} elements."
let n = hailstone(i).len
let first = h[0..3].join(", ")
if n > m:
let last = h[^4..^1].join(", ")
m = n
echo &"This sequence begins with {first} and ends with {last}."
mi = i
 
echo "Maximum length ", m, " was found for hailstone(", mi, ") for numbers <100,000"</lang>
var m, mi = 0
for i in 1..<100_000:
let n = hailstone(i).len
if n > m:
m = n
mi = i
echo &"\nFor numbers < 100_000, maximum length {m} was found for Hailstone({mi})."</syntaxhighlight>
{{out}}
<pre>Hailstone sequence for number 27 has 112 elements.
<pre>Maximum length 351 was found for hailstone(77031) for numbers <100,000</pre>
This sequence begins with 27, 82, 41, 124 and ends with 8, 4, 2, 1.
 
For numbers < 100_000, maximum length 351 was found for Hailstone(77031).</pre>
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">MODULE hailst;
 
IMPORT Out;
Line 5,084 ⟶ 7,241:
Out.String ("Done.");
Out.Ln
END hailst.</langsyntaxhighlight>
Producing
<pre>
Line 5,112 ⟶ 7,269:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#load "nums.cma";;
open Num;;
 
Line 5,174 ⟶ 7,331:
"1732"; "866"; "433"; "1300"; "650"; "325"; "976"; "488"; "244"; "122";
"61"; "184"; "92"; "46"; "23"; "70"; "35"; "106"; "53"; "160"; "80"; "40";
"20"; "10"; "5"; "16"; "8"; "4"; "2"; "1"] *)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: hailstone // n -- [n]
| l |
ListBuffer new ->l
Line 5,185 ⟶ 7,342:
 
hailstone(27) dup size println dup left(4) println right(4) println
100000 seq map(#[ dup hailstone size swap Pair new ]) reduce(#maxKey) println</langsyntaxhighlight>
 
{{out}}
Line 5,194 ⟶ 7,351:
[351, 77031]
</pre>
 
=={{header|Onyx (wasm)}}==
<syntaxhighlight lang="C">
use core { * }
 
hailstone :: (n: u32) -> [..]u32 {
seq: [..]u32;
array.push(&seq, n);
while n > 1 {
n = n/2 if n%2 == 0 else (n*3)+1;
array.push(&seq, n);
}
return seq;
}
 
Longest :: struct { num, len : u32; }
 
main :: () {
// -------
// task 1:
// -------
// "Create a routine to generate the hailstone
// sequence for a number."
i := 27;
seq := hailstone(i);
printf("Task 1:\n{}: {}\n\n",
i,
seq
);
// -------
// task 2:
// -------
// "Use the routine to show that the hailstone
// sequence for the number 27 has
// 112 elements starting with
// 27, 82, 41, 124 and ending with 8, 4, 2, 1"
slice_size := 4;
len := seq.length;
slice_first := seq[0..slice_size];
slice_last := seq[seq.length-slice_size..seq.length];
printf("Task 2:\nlength: {}, first: {}, last: {}\n\n",
len,
slice_first,
slice_last
);
// -------
// task 3:
// -------
// "Show the number less than 100,000
// which has the longest hailstone sequence
// together with that sequences length."
l : Longest;
for i in 1..100000 {
seq := hailstone(i);
if l.len < seq.length { l = .{num = i, len = seq.length}; }
}
printf("Task 3:\nLongest Num: {}, Sequence Length: {}\n", l.num, l.len);
}
</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
sequence = hailstone(27)
say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]"
Line 5,224 ⟶ 7,446:
end
return sequence
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,233 ⟶ 7,455:
=={{header|Order}}==
To display the length, and first and last elements, of the hailstone sequence for 27, we could do this:
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8hailstone ORDER_PP_FN( \
Line 5,249 ⟶ 7,471:
8(starts with:) 8seq_take(4, 8H) 8comma 8space
8(ends with:) 8seq_drop(8minus(8S, 4), 8H))
) )</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">h(27) - length:112, starts with:(27)(82)(41)(124), ends with:(8)(4)(2)(1)</langsyntaxhighlight>
 
Unfortunately, the C preprocessor not really being designed with large amounts of garbage collection in mind, trying to compute the hailstone sequences up to 100000 is almost guaranteed to run out of memory (and take a very, very long time). If we wanted to try, we could add this to the program, which in most languages would use relatively little memory:
<langsyntaxhighlight lang="c">#define ORDER_PP_DEF_8h_longest ORDER_PP_FN( \
8fn(8M, 8P, \
8if(8is_0(8M), \
Line 5,266 ⟶ 7,488:
8let((8P, 8h_longest(8nat(1,0,0,0,0,0), 8pair(0, 0))),
8pair(8to_lit(8tuple_at_0(8P)), 8to_lit(8tuple_at_1(8P))))
)</langsyntaxhighlight>
 
...or even this "more elegant" version, which will run out of memory very quickly indeed (but in practice seems to work better for smaller ranges):
<langsyntaxhighlight lang="c">ORDER_PP(
8let((8P,
8seq_head(
Line 5,277 ⟶ 7,499:
8pair(8N, 8seq_size(8hailstone(8N)))),
8seq_iota(1, 8nat(1,0,0,0,0,0)))))),
8pair(8to_lit(8tuple_at_0(8P)), 8to_lit(8tuple_at_1(8P)))) )</langsyntaxhighlight>
 
Notice that large numbers (>100) must be entered as digit sequences with <code>8nat</code>. <code>8to_lit</code> converts a digit sequence back to a readable number.
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {HailstoneSeq N}
N > 0 = true %% assert
Line 5,305 ⟶ 7,527:
MaxI#MaxLen = {List.foldL Pairs MaxBy2nd 0#0}
{System.showInfo
"Maximum length "#MaxLen#" was found for hailstone("#MaxI#")"}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,314 ⟶ 7,536:
 
===Version #1.===
<langsyntaxhighlight lang="parigp">show(n)={
my(t=1);
while(n>1,
Line 5,344 ⟶ 7,566:
 
show(27)
r=0;for(n=1,1e5,t=len(n);if(t>r,r=t;ra=n));print(ra"\t"r)</langsyntaxhighlight>
{{out}}
<pre>27,82,41,124,62,31,94,47,142,71,214,107,322,161,484,242,121,364,182,91,274,137,4
Line 5,362 ⟶ 7,584:
[http://oeis.org/A070165 A070165]
 
<langsyntaxhighlight lang="parigp">
\\ Get vector with Collatz sequence for the specified starting number.
\\ Limit vector to the lim length, or less, if 1 (one) term is reached (when lim=0).
Line 5,385 ⟶ 7,607:
Collatzmax(1,100000);
}
</syntaxhighlight>
</lang>
 
{{Output}}
Line 5,401 ⟶ 7,623:
See [[Hailstone_sequence#Delphi | Delphi]]
or try this transformed Delphi version without generics.Use of a static array.
<langsyntaxhighlight lang="pascal">program ShowHailstoneSequence;
{$IFDEF FPC}
{$MODE delphi} //or objfpc
Line 5,509 ⟶ 7,731:
limit := limit*10;
until Limit > maxN;
end.</langsyntaxhighlight>
{{out}}
<pre>sequence of 27 has 112 elements
Line 5,530 ⟶ 7,752:
=={{header|Perl}}==
=== Straightforward ===
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
 
use warnings;
Line 5,566 ⟶ 7,788:
 
return @sequence;
}</langsyntaxhighlight>
 
{{out}}
Line 5,577 ⟶ 7,799:
=== Compact ===
A more compact version:
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict;
 
Line 5,591 ⟶ 7,813:
@h = ();
for (1 .. 99_999) { @h = ($_, $h[2]) if ($h[2] = hailstone($_)) > $h[1] }
printf "%d: (%d)\n", @h;</langsyntaxhighlight>
 
The same approach as in the compact version above, obfuscated:
<lang Perl>sub _{my$_=$_[''];push@_,$_&1?$_+=$_++<<1:($_>>=1)while$_^1;@_}
@_=_($_=031^2);print "$_: @_[0..3] ... @_[-4..-1] (".@_.")\n";
$_[1]<($_[2]=_($_))and@_=($_,$_[2])for 1..1e5-1;printf "%d: (%d)\n", @_;</lang>
 
{{out}}
Line 5,602 ⟶ 7,820:
27: 27 82 41 124 ... 8 4 2 1 (112)
77031: (351)
</pre>
 
=={{header|Perl 6}}==
 
<lang perl6>sub hailstone($n) { $n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1 }
 
my @h = hailstone(27);
say "Length of hailstone(27) = {+@h}";
say ~@h;
 
my $m = max (+hailstone($_) => $_ for 1..99_999);
say "Max length {$m.key} was found for hailstone({$m.value}) for numbers < 100_000";</lang>
 
{{out}}
<pre>
Length of hailstone(27) = 112
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
Max length 351 was found for hailstone(77031) for numbers < 100_000
</pre>
 
=={{header|Phix}}==
Copy of [[Hailstone_sequence#Euphoria|Euphoria]]
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function hailstone(atom n)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence s = {n}
<span style="color: #008080;">function</span> <span style="color: #000000;">hailstone</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
while n!=1 do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}</span>
if remainder(n,2)=0 then
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
n /= 2
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">n</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
n = 3*n+1
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
s &= n
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
return s
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function hailstone_count(atom n)
integer count = 1
<span style="color: #008080;">function</span> <span style="color: #000000;">hailstone_count</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
while n!=1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
if remainder(n,2)=0 then
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
n /= 2
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">n</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
n = 3*n+1
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
count += 1
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
return count
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">count</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence s = hailstone(27)
integer ls = length(s)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">hailstone</span><span style="color: #0000FF;">(</span><span style="color: #000000;">27</span><span style="color: #0000FF;">)</span>
s[5..-5] = {".."}
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"hailstone(27) = %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"numbers"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)})</span>
puts(1,"hailstone(27) = ")
? s
<span style="color: #004080;">integer</span> <span style="color: #000000;">hmax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">imax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span>
printf(1,"length = %d\n\n",ls)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1e5</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
 
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">hailstone_count</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
integer hmax = 1, imax = 1,count
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">></span><span style="color: #000000;">hmax</span> <span style="color: #008080;">then</span>
for i=2 to 1e5-1 do
<span style="color: #000000;">hmax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">count</span>
count = hailstone_count(i)
<span style="color: #000000;">imax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
if count>hmax then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
hmax = count
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
imax = i
end if
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The longest hailstone sequence under 100,000 is %d with %d elements.\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">imax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hmax</span><span style="color: #0000FF;">})</span>
end for
<!--</syntaxhighlight>-->
 
printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",{imax,hmax})</lang>
{{out}}
<pre>
hailstone(27) = {27,82,41,124,"...",8,4,2,1," (112 numbers)"}
The longest hailstone sequence under 100,000 is 77031 with 351 elements.
length = 112
 
The longest hailstone sequence under 100,000 is 77031 with 351 elements.
</pre>
 
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function hailstone($n,$seq=array()){
$sequence = $seq;
$sequence[] = $n;
Line 5,702 ⟶ 7,898:
foreach($maxResult as $key => $val){
echo 'Number < 100000 with longest Hailstone seq.: ' . $key . ' with length of ' . $val;
}</langsyntaxhighlight>
<pre>
112 Elements.
Line 5,708 ⟶ 7,904:
Number < 100000 with longest Hailstone seq.: 77031 with length of 351
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
 
go =>
println("H27:"),
H27 = hailstoneseq(27),
H27Len = H27.len,
println(len=H27.len),
println(take(H27,4)++['...']++drop(H27,H27Len-4)),
nl,
 
println("Longest sequence < 100_000:"),
longest_seq(99_999),
 
nl.
 
% The Hailstone value of a number
hailstone(N) = N // 2, N mod 2 == 0 => true.
hailstone(N) = 3*N+1, N mod 2 == 1 => true.
 
% Sequence for a number
hailstoneseq(N) = Seq =>
Seq := [N],
while (N > 1)
N := hailstone(N),
Seq := Seq ++ [N]
end.
 
%
% Use a map to cache the lengths.
% Here we don't care about the actual sequence.
%
longest_seq(Limit) =>
Lens = new_map(), % caching the lengths
MaxLen = 0,
MaxN = 1,
 
foreach(N in 1..Limit-1)
M = N,
CLen = 1,
while (M > 1)
if Lens.has_key(M) then
CLen := CLen + Lens.get(M) - 1,
M := 1
else
M := hailstone(M), % call the
CLen := CLen + 1
end
end,
Lens.put(N, CLen),
if CLen > MaxLen then
MaxLen := CLen,
MaxN := N
end
end,
println([maxLen=MaxLen, maxN=MaxN]),
nl.</syntaxhighlight>
 
{{out}}
<pre>H27:
len = 112
[27,82,41,124,...,8,4,2,1]
 
Longest sequence < 100_000:
[maxLen = 351,maxN = 77031]</pre>
 
===Mode-directed tabling===
If we just want to get the length of the longest sequence - and are not forced to use the same Hailstone function as for the H27 task - then this version using model-directed tabling is faster than longest_seq/1: 0.055s vs 0.127s. (Original idea by Neng-Fa Zhou.)
<syntaxhighlight lang="picat">go2 =>
time(max_chain(MaxN,MaxLen)),
printf("MaxN=%w,MaxLen=%w%n",MaxN,MaxLen).
 
table (-,max)
max_chain(N,Len) =>
between(2,99_999,N),
gen(N,Len).
 
table (+,-)
gen(1,Len) => Len=1.
gen(N,Len), N mod 2 == 0 =>
gen(N div 2,Len1),
Len=Len1+1.
gen(N,Len) =>
gen(3*N+1,Len1),
Len=Len1+1.
</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de hailstone (N)
(make
(until (= 1 (link N))
Line 5,722 ⟶ 8,005:
 
(let N (maxi '((N) (length (hailstone N))) (range 1 100000))
(println N (length (hailstone N))) )</langsyntaxhighlight>
{{out}}
<pre>27 112 (27 82 41 124) - (8 4 2 1)
Line 5,728 ⟶ 8,011:
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">#!/usr/bin/env pike
 
int next(int n)
Line 5,766 ⟶ 8,049:
}
write("longest sequence starting at %d has %d elements\n", longest->start, longest->length);
}</langsyntaxhighlight>
 
{{out}}
Line 5,775 ⟶ 8,058:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">test: proc options (main);
declare (longest, n) fixed (15);
declare flag bit (1);
Line 5,812 ⟶ 8,095:
end hailstones;
 
end test;</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 5,930 ⟶ 8,213:
The hailstone sequence has length 112
77031 has the longest sequence of 351
</pre>
 
==={{header|PL/I-80}}===
<syntaxhighlight lang="pl/i">hailstone_demo: proc options (main);
%replace
true by '1'b,
false by '0'b;
dcl
(slen, longest) fixed bin(15),
(n, n_longest,limit) fixed decimal(12),
answer char(1);
put skip list ('Display hailstone sequence for what number? ');
get list (n);
slen = hailstone(n, true);
put skip list ('Sequence length = ', slen);
put skip(2) list ('Search for longest sequence (y/n)? ');
get list (answer);
if ((answer ^= 'y') & (answer ^= 'Y')) then stop;
put list ('Search to what limit? ');
get list (limit);
longest = 1;
n = 2;
do while (n < limit);
slen = hailstone(n, false);
if slen > longest then
do;
longest = slen;
n_longest = n;
end;
n = n + 1;
end;
put skip edit ('Longest sequence =',longest,' for n =',n_longest)
(a,f(4),a,f(6));
 
 
/* compute, and optionally display, hailstone sequence for n */
hailstone:
procedure(n, show) returns (fixed binary);
dcl
(len, col) fixed binary,
(n, k) fixed decimal(12),
show bit(1);
/* make local copy since n is passed by reference */
k = n;
col = 1;
len = 1;
do while ((k ^= 1) & (k > 0));
if (show) then /* print 8 columns across */
do;
put edit (k) (f(8));
col = col + 1;
if col > 8 then
do;
put skip;
col = 1;
end;
end;
if (mod(k,2) = 0) then
k = k / 2;
else
k = k * 3 + 1;
len = len + 1;
end;
if (show) then put edit (k) (f(8));
return (len);
end hailstone;
 
end hailstone_demo;
</syntaxhighlight>
{{out}}
<pre>Display hailstone sequence for what number? 27
27 82 41 124 62 31 94 47
142 71 214 107 322 161 484 242
121 364 182 91 274 137 412 206
103 310 155 466 233 700 350 175
526 263 790 395 1186 593 1780 890
445 1136 668 334 167 502 251 754
377 1132 566 283 850 425 1276 638
319 958 479 1438 719 2158 1079 3238
1619 4858 2429 7288 3644 1822 911 2734
1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325
976 488 244 122 61 184 92 46
23 70 35 106 53 160 80 40
20 10 5 16 8 4 2 1
Sequence length = 112
 
Search for longest sequence (y/n)? y
Search to what limit? 100000
Longest sequence = 351 for n = 77031
</pre>
 
=={{header|plainTeX}}==
The following code works with any TeX engine.
<langsyntaxhighlight lang="tex">\newif\ifprint
\newcount\itercount
\newcount\currentnum
Line 5,970 ⟶ 8,343:
\repeat
Seed max = \seed, length = \lenmax
\bye</langsyntaxhighlight>
 
pdf or dvi output:
Line 5,982 ⟶ 8,355:
Seed max = 77031, length = 351
</pre>
 
=={{header|Pointless}}==
<syntaxhighlight lang="pointless">output =
println(format(fmt,
[seqLength, initSeq, tailSeq] ++ toList(longestPair)
))
 
fmt = """getSeq(27) (length): {}
getSeq(27) (first 4): {}
getSeq(27) (last 4): {}
max length {} for n = {}"""
 
-----------------------------------------------------------
seq = getSeq(27)
seqLength = length(seq)
initSeq = take(4, seq)
tailSeq = drop(seqLength - 4, seq)
-----------------------------------------------------------
longestPair =
range(1, 99999)
|> map(n => (length(getSeq(n)), n))
|> argmax(at(0))
-----------------------------------------------------------
-- generate full sequence
getSeq(n) =
iterate(step, n)
|> takeUntil(eq(1))
-----------------------------------------------------------
-- get the next number in a sequence
step(n) =
if n % 2 == 0 then round(n / 2) else n * 3 + 1</syntaxhighlight>
 
{{out}}
<pre>getSeq(27) (length): 112
getSeq(27) (first 4): [27, 82, 41, 124]
getSeq(27) (last 4): [8, 4, 2, 1]
max length 351 for n = 77031</pre>
 
=={{header|PowerShell}}==
{{works with|PowerShell|3.0+}}
<syntaxhighlight lang="powershell">
<lang Powershell>
 
function Get-HailStone {
Line 6,006 ⟶ 8,423:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 6,029 ⟶ 8,446:
=={{header|Prolog}}==
1. Create a routine to generate the hailstone sequence for a number.
<langsyntaxhighlight lang="prolog">hailstone(1,[1]) :- !.
hailstone(N,[N|S]) :- 0 is N mod 2, N1 is N / 2, hailstone(N1,S).
hailstone(N,[N|S]) :- 1 is N mod 2, N1 is (3 * N) + 1, hailstone(N1, S).</langsyntaxhighlight>
 
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1.
 
The following query performs the test.
<langsyntaxhighlight lang="prolog">hailstone(27,X),
length(X,112),
append([27, 82, 41, 124], _, X),
append(_, [8, 4, 2, 1], X).</langsyntaxhighlight>
 
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequences length.
<langsyntaxhighlight lang="prolog">longestHailstoneSequence(M, Seq, Len) :- longesthailstone(M, 1, 1, Seq, Len).
longesthailstone(1, Cn, Cl, Mn, Ml):- Mn = Cn,
Ml = Cl.
Line 6,051 ⟶ 8,468:
longesthailstone(N1, N, L, Mn, Ml).
longesthailstone(N, Cn, Cl, Mn, Ml) :- N1 is N-1,
longesthailstone(N1, Cn, Cl, Mn, Ml).</langsyntaxhighlight>
run this query.
<langsyntaxhighlight lang="prolog">longestHailstoneSequence(100000, Seq, Len).</langsyntaxhighlight>
to get the following result
<pre>
Line 6,064 ⟶ 8,481:
Works with SWI-Prolog and module '''chr''' written by '''Tom Schrijvers''' and '''Jan Wielemaker''' <br>
 
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(chr)).
:- chr_option(debug, off).
:- chr_option(optimize, full).
Line 6,080 ⟶ 8,497:
% Hailstone loop
hailstone(1) ==> true.
hailstone(N) ==> N \= 1 | collatz(N, H), hailstone(H).</langsyntaxhighlight>
 
Code for task one :
<langsyntaxhighlight Prologlang="prolog">task1 :-
hailstone(27),
findall(X, find_chr_constraint(hailstone(X)), L),
clean,
% check the requirements
( (length(L, 112), append([27, 82, 41, 124 | _], [8,4,2,1], L)) -> writeln(ok); writeln(ko)).</langsyntaxhighlight>
{{out}}
<pre> ?- task1.
Line 6,094 ⟶ 8,511:
true.</pre>
Code for task two :
<langsyntaxhighlight Prologlang="prolog">longest_sequence :-
seq(2, 100000, 1-[1], Len-V),
format('For ~w sequence has ~w len ! ~n', [V, Len]).
Line 6,115 ⟶ 8,532:
findall(hailstone(X), find_chr_constraint(hailstone(X)), L),
length(L, Len),
clean.</langsyntaxhighlight>
{{out}}
<pre> ?- longest_sequence.
Line 6,123 ⟶ 8,540:
 
=={{header|Pure}}==
<langsyntaxhighlight lang="pure">// 1. Create a routine to generate the hailstone sequence for a number.
type odd x::int = x mod 2;
type even x::int = ~odd x;
Line 6,151 ⟶ 8,568:
(foldr (\ (a,b) (c,d) -> if (b > d) then (a,b) else (c,d))
(0,0)
(map (\ x -> (x, # hailstone x)) (1..100000)));</langsyntaxhighlight>
{{out}}
<pre>
Line 6,159 ⟶ 8,576:
 
=={{header|Python}}==
===Procedural===
<lang python>def hailstone(n):
<syntaxhighlight lang="python">def hailstone(n):
seq = [n]
while n > 1:
n = 3 * n + 1 if n & 1 else n // 2
seq.append(n)
return seq
 
 
if __name__ == '__main__':
h = hailstone(27)
assert (len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]112
and h[:4] == [27, 82, 41, 124]
print("Maximum length %i was found for hailstone(%i) for numbers <100,000" %
and h[-4:] == [8, 4, 2, 1])
max((len(hailstone(i)), i) for i in range(1,100000)))</lang>
max_length, n = max((len(hailstone(i)), i) for i in range(1, 100_000))
print(f"Maximum length {max_length} was found for hailstone({n}) "
f"for numbers <100,000")</syntaxhighlight>
 
{{out}}
<pre>Maximum length 351 was found for hailstone(77031) for numbers <100,000</pre>
 
===Using a generator===
<syntaxhighlight lang="python">from itertools import islice
 
 
def hailstone(n):
yield n
while n > 1:
n = 3 * n + 1 if n & 1 else n // 2
yield n
 
 
if __name__ == '__main__':
h = hailstone(27)
assert list(islice(h, 4)) == [27, 82, 41, 124]
for _ in range(112 - 4 * 2):
next(h)
assert list(islice(h, 4)) == [8, 4, 2, 1]
max_length, n = max((sum(1 for _ in hailstone(i)), i)
for i in range(1, 100_000))
print(f"Maximum length {max_length} was found for hailstone({n}) "
f"for numbers <100,000")</syntaxhighlight>
 
{{out}}
<pre>Maximum length 351 was found for hailstone(77031) for numbers <100,000</pre>
 
 
===Composition of pure functions===
{{Works with|Python|3.7}}
<syntaxhighlight lang="python">'''Hailstone sequences'''
 
from itertools import (islice, takewhile)
 
 
# hailstone :: Int -> [Int]
def hailstone(x):
'''Hailstone sequence starting with x.'''
def p(n):
return 1 != n
return list(takewhile(p, iterate(collatz)(x))) + [1]
 
 
# collatz :: Int -> Int
def collatz(n):
'''Next integer in the hailstone sequence.'''
return 3 * n + 1 if 1 & n else n // 2
 
 
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Tests.'''
 
n = 27
xs = hailstone(n)
print(unlines([
f'The hailstone sequence for {n} has {len(xs)} elements,',
f'starting with {take(4)(xs)},',
f'and ending with {drop(len(xs) - 4)(xs)}.\n'
]))
 
(a, b) = (1, 99999)
(i, x) = max(
enumerate(
map(compose(len)(hailstone), enumFromTo(a)(b))
),
key=snd
)
print(unlines([
f'The number in the range {a}..{b} '
f'which produces the longest sequence is {1 + i},',
f'generating a hailstone sequence of {x} integers.'
]))
 
 
# ----------------------- GENERIC ------------------------
 
# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
def compose(g):
'''Function composition.'''
return lambda f: lambda x: g(f(x))
 
 
# drop :: Int -> [a] -> [a]
# drop :: Int -> String -> String
def drop(n):
'''The sublist of xs beginning at
(zero-based) index n.
'''
def go(xs):
if isinstance(xs, (list, tuple, str)):
return xs[n:]
else:
take(n)(xs)
return xs
return go
 
 
# enumFromTo :: (Int, Int) -> [Int]
def enumFromTo(m):
'''Integer enumeration from m to n.'''
return lambda n: range(m, 1 + n)
 
 
# iterate :: (a -> a) -> a -> Gen [a]
def iterate(f):
'''An infinite list of repeated
applications of f to x.
'''
def go(x):
v = x
while True:
yield v
v = f(v)
return go
 
 
# snd :: (a, b) -> b
def snd(tpl):
'''Second component of a tuple.'''
return tpl[1]
 
 
# take :: Int -> [a] -> [a]
# take :: Int -> String -> String
def take(n):
'''The prefix of xs of length n,
or xs itself if n > length xs.
'''
def go(xs):
return (
xs[0:n]
if isinstance(xs, (list, tuple))
else list(islice(xs, n))
)
return go
 
 
# unlines :: [String] -> String
def unlines(xs):
'''A single newline-delimited string derived
from a list of strings.'''
return '\n'.join(xs)
 
 
if __name__ == '__main__':
main()</syntaxhighlight>
{{Out}}
<pre>The hailstone sequence for 27 has 112 elements,
starting with [27, 82, 41, 124],
and ending with [8, 4, 2, 1].
 
The number in the range 1..99999 which produces the longest sequence is 77031,
generating a hailstone sequence of 351 integers.</pre>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">[ 1 & ] is odd ( n --> b )
[ []
[ over join swap
dup 1 > while
dup odd iff
[ 3 * 1 + ]
else
[ 2 / ]
swap again ]
drop ] is hailstone ( n --> [ )
 
[ stack ] is longest ( --> s )
 
[ stack ] is length ( --> s )
 
27 hailstone
say "The hailstone sequence for 27 has "
dup size echo say " elements." cr
say "It starts with"
dup 4 split drop witheach [ sp echo ]
say " and ends with"
-4 split nip witheach [ sp echo ]
say "." cr cr
 
0 longest put 0 length put
99999 times
[ i^ 1+ hailstone size
dup length share > if
[ dup length replace
i^ 1+ longest replace ]
drop ]
longest take echo
say " has the longest sequence of any number less than 100000."
cr say "It is " length take echo say " elements long." cr</syntaxhighlight>
 
'''Output:'''
<syntaxhighlight lang="quackery">The hailstone sequence for 27 has 112 elements.
It starts with 27 82 41 124 and ends with 8 4 2 1.
 
77031 has the longest sequence of any number less than 100000.
It is 351 elements long.
</syntaxhighlight>
 
=={{header|R}}==
===Iterative solution===
<lang r>### PART 1:
<syntaxhighlight lang="rsplus">### PART 1:
makeHailstone <- function(n){
hseq <- n
Line 6,209 ⟶ 8,831:
cat("Between ", lower.bound, " and ", upper.bound, ", the input of ",
max.index, " gives the longest hailstone sequence, which has length ",
max.length, ". \n", sep="")</langsyntaxhighlight>
 
{{out}}
Line 6,227 ⟶ 8,849:
Between 1 and 1e+05, the input of 77031 gives the longest hailstone sequence,
which has length 351.</pre>
===Vectorization solution===
The previous solution is entirely satisfactory and may be more efficient than the following solution. However, problems like these are a great chance to show off the strength of R's vectorization. Also, this lets us show off how the <- syntax can do multiple variable assignments in one line. Observe how short the following code is:
<syntaxhighlight lang="rsplus">###Task 1:
collatz <- function(n)
{
lastIndex <- 1
output <- lastEntry <- n
while(lastEntry != 1)
{
#Each branch updates lastEntry, lastIndex, and appends a new element to the end of output.
#Note that the return value of lastIndex <- lastIndex + 1 is lastIndex + 1.
#You may be surprised that output can be appended to despite starting as just a single number.
#If so, recall that R's numerics are vectors, meaning that output<-n created a vector of length 1.
#It's ugly, but efficient.
if(lastEntry %% 2) lastEntry <- output[lastIndex <- lastIndex + 1] <- 3 * lastEntry + 1
else lastEntry <- output[lastIndex <- lastIndex + 1] <- lastEntry %/% 2
}
output
}
 
###Task 2:
#Notice how easy it is to access the required elements:
twentySeven <- collatz(27)
cat("The first four elements are:", twentySeven[1:4], "and the last four are:", twentySeven[length(twentySeven) - 3:0], "\n")
 
###Task 3:
#Notice how a several line long loop can be avoided with R's sapply or Vectorize:
seqLenghts <- sapply(seq_len(99999), function(x) length(collatz(x)))
longest <- which.max(seqLenghts)
cat("The longest sequence before the 100000th is found at n =", longest, "and it has length", seqLenghts[longest], "\n")
#Equivalently, line 1 could have been: seqLenghts <- sapply(Vectorize(collatz)(1:99999), length).
#Another good option would be seqLenghts <- lengths(Vectorize(collatz)(1:99999)).</syntaxhighlight>
{{out}}
<pre>The first four elements are: 27 82 41 124 and the last four are: 8 4 2 1
The longest sequence before the 100000th is found at n = 77031 and it has length 351</pre>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 6,250 ⟶ 8,907:
(printf "for x<=~s, ~s has the longest sequence with ~s items\n"
N (car longest) (cdr longest))
</syntaxhighlight>
</lang>
 
{{out}}
Line 6,256 ⟶ 8,913:
h(27) = (27 82 41 124 ... 8 4 2 1), 112 items
for x<=100000, 77031 has the longest sequence with 351 items
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
<syntaxhighlight lang="raku" line>sub hailstone($n) { $n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1 }
 
my @h = hailstone(27);
say "Length of hailstone(27) = {+@h}";
say ~@h;
 
my $m = max ( (1..99_999).race.map: { +hailstone($_) => $_ } );
say "Max length {$m.key} was found for hailstone({$m.value}) for numbers < 100_000";</syntaxhighlight>
 
{{out}}
<pre>
Length of hailstone(27) = 112
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
Max length 351 was found for hailstone(77031) for numbers < 100_000
</pre>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">
hail: func [
"Returns the hailstone sequence for n"
Line 6,290 ⟶ 8,966:
"the number less than 100000 with the longest hail sequence is"
maxN "with length" maxLen
]</langsyntaxhighlight>
 
{{out}}
<pre>the hail sequence of 27 has length 112 and has the form 27 82 41 ... 4 2 1
the number less than 100000 with the longest hail sequence is 77031 with length 351</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <ShowHailstone 27>
<ShowLongest 100000>;
}
 
Hailstone {
1 = 1;
s.N, <Mod s.N 2>: {
0 = s.N <Hailstone <Div s.N 2>>;
1 = s.N <Hailstone <+ 1 <* 3 s.N>>>;
};
};
 
ShowHailstone {
s.N, <Hailstone s.N>: e.Seq,
<Lenw e.Seq>: s.Len s.1 s.2 s.3 s.4 e.X s.D4 s.D3 s.D2 s.D1
= <Prout 'The hailstone sequence for the number '
<Symb s.N> ' has ' <Symb s.Len> ' elements,\n'
'starting with ' s.1 s.2 s.3 s.4
'and ending with ' s.D4 s.D3 s.D2 <Symb s.D1>'.'>;
}
 
FindLongest {
s.Max = <FindLongest s.Max 1 1 1>;
s.Max s.Max s.Long s.Len = s.Long s.Len;
s.Max s.Cur s.Long s.Len,
<Hailstone s.Cur>: e.CurSeq,
<Lenw e.CurSeq>: s.CurLen e.X,
<+ s.Cur 1>: s.Next,
<Compare s.CurLen s.Len>: {
'+' = <FindLongest s.Max s.Next s.Cur s.CurLen>;
s.X = <FindLongest s.Max s.Next s.Long s.Len>;
};
};
 
ShowLongest {
s.Max, <FindLongest s.Max>: s.Long s.Len
= <Prout 'The number < ' <Symb s.Max> ' which has the longest'
' hailstone sequence is ' <Symb s.Long> '.\n'
'The length of its Hailstone sequence is '
<Symb s.Len> '.'>;
};</syntaxhighlight>
{{out}}
<pre>The hailstone sequence for the number 27 has 112 elements,
starting with 27 82 41 124 and ending with 8 4 2 1.
The number < 100000 which has the longest hailstone sequence is 77031.
The length of its Hailstone sequence is 351.</pre>
 
=={{header|REXX}}==
===non-optimized===
<langsyntaxhighlight REXXlang="rexx">/*REXX program tests a number and also a range for hailstone (Collatz) sequences. */
numeric digits 20 /*be able to handle gihugeic numbers. */
parse arg x y . /*get optional arguments from the C.L. */
if x=='' | x=="," then x= 27 /*No 1st argument? Then use default.*/
if y=='' | y=="," then y= 100000 - 1 /* " 2nd " " " " */
$= hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/
say x ' has a hailstone sequence of ' words($)
say ' and starts with: ' subword($, 1, 4) " ∙∙∙"
say ' and ends with: ∙∙∙' subword($, max(5, words($)-3))
if y==0 then exit /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 2▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/
say
w= 0; do j=1 for y; call hailstone j /*traipse through the range of numbers.*/
call hailstone j /*compute the hailstone sequence for J.*/
if #hs<=w then iterate /*Not big 'nuff? Then keep traipsing.*/
bigJ= j; w= #hs /*remember what # has biggest hailstone*/
end /*j*/
say '(between 1 ──►' y") " bigJ ' has the longest hailstone sequence: ' w
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hailstone: procedure expose #hs; parse arg n 1 s /*N and S: are set to the 1st argument.*/
do #hs=1 while n\==1 /*keep loop while N isn't unity. */
if n//2 then n= n * 3 + 1 /*N is odd ? Then calculate 3*n + 1 */
else n= n %2 2 /*" " even? Then calculate fast ÷ */
s= s n /* [↑] % is REXX integer division. */
end /*#hs*/ /* [↑] append N to the sequence list*/
return s /*return the S string to the invoker.*/</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the default inputs:}}
<pre>
27 has a hailstone sequence of 112
Line 6,334 ⟶ 9,058:
 
===optimized===
This version is overabout fifteen&nbsp; '''7''' &nbsp; times faster than the previous (unoptimized) version.
 
It makes use of:
::::* &nbsp; previously calculated Collatz sequences (memoization)
::::* &nbsp; a faster method of determining if an integer is even
<langsyntaxhighlight REXXlang="rexx">/*REXX program tests a number and also a range for hailstone (Collatz) sequences. */
!.=0; !.0=1; !.2=1; !.4=1; !.6=1; !.8=1 /*assign even numerals to be "true". */
numeric digits 20; @.=0 0 /*handle big numbers; initialize array.*/
parse arg x y z .; !.h=y y /*get optional arguments from the C,.L. */
if x=='' | x=="," then x= 27 27 /*No 1st argument? Then use default.*/
if y=='' | y=="," then y= 100000 - 1 /* " 2nd " " " " */
if z=='' | z=="," then z= 12 12 /*head/tail number? " " " */
hm= max(y, 40000500000) /*use memoization (maximum num for @.)*/
$= hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/
say x ' has a hailstone sequence of ' words($)
say ' and starts with: ' subword($, 1, z) " ∙∙∙"
say ' and ends with: ∙∙∙' subword($, max(z+1, words($)-z+1))
if y==0 then exit /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 2▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/
say
w= 0; do j=1 for y; $= hailstone(j) /*traipse through the range of numbers.*/
#hs= words($) /*find the length of the hailstone seq.*/
if #hs<=w then iterate /*Not big enough? Then keep traipsing.*/
bigJ= j; w= #hs /*remember what # has biggest hailstone*/
end /*j*/
say '(between 1 ──►' y") " bigJ ' has the longest hailstone sequence: ' w
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hailstone: procedure expose @. !. hm; parse arg n 1 s 1 o,@.1 /*N,S,O: are the 1st arg*/
do while @.n==0 /*loop while the residual is unknown. */
parse var n '' -1 L /*extract the last decimal digit of N.*/
if !.L then n= n % 2 /*N is even? Then calculate fast ÷ */
else n= n * 3 + 1 1 /*" " odd ? " " 3*n + 1 */
s= s n /* [↑] %: is the REXX integer division*/
end /*while*/ /* [↑] append N to the sequence list*/
s=s s @.n /*append the number to a sequence list.*/
@.o= subword(s, 2); parse var s _ r /*use memoization for this hailstone #.*/
do while r\==''; parse var r _ r /*obtain the next hailstone sequence. */
if @._\==0 then leave /*Was number already found? Return S.*/
if _>hm then iterate /*Is number out of range? Ignore it.*/
@._=r r /*assign subsequence number to array. */
end /*while*/; return s</syntaxhighlight>
return s</lang>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 6,382 ⟶ 9,105:
and ends with: ∙∙∙ 53 160 80 40 20 10 5 16 8 4 2 1
 
(between 1─►1 ──► 99999) 77031 has the longest hailstone sequence: 351
</pre>
'''{{out|output''' |text=&nbsp; when using the inputs: &nbsp; &nbsp; <tt> , &nbsp; 1000000 </tt>}}
<pre>
27 has a hailstone sequence of 112
Line 6,394 ⟶ 9,117:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
size = 27
aList = []
Line 6,415 ⟶ 9,138:
see "" + aList[i] + " "
next
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
HP-28 emulator's timedog preventing from longlasting code execution, the third item of the task is achieved by calculating the 1-100,000 sequence in increments of 5,000 numbers, with a derivative of the generator that only provides the length of the sequence to increase execution speed.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code
! Comments
|-
|
DUP 1 →LIST SWAP
'''WHILE''' DUP 1 ≠ '''REPEAT'''
'''IF''' DUP 2 MOD '''THEN''' 3 * 1 + '''ELSE''' 2 / '''END'''
SWAP OVER + SWAP
'''END''' DROP
≫ 'SYRAQ' STO
1 SWAP '''WHILE''' DUP 1 ≠ '''REPEAT'''
'''IF''' DUP 2 MOD '''THEN''' 3 * 1 + '''ELSE''' 2 / '''END'''
SWAP 1 + SWAP
'''END''' DROP
≫ 'SYRAF' STO
≪ SyMax SYRAF SWAP
DUP 5000 + DUP 4 ROLLD '''FOR''' n
'''IF''' DUP n SYRAF <
'''THEN'''
DROP n SYRAF n 'SyMax' STO
'''END NEXT''' DROP ≫
'SYR5K' STO
|
''( n -- { sequence } )''
initialize sequence with n
Calculate next element
Store it into sequence
Forget n
''( n -- sequence_length )''
Initialize counter
Calculate next element
Increment counter
Forget n
''( n -- n+10000 )''
Initialize loop
If sequence length greater than previous ones...
... memorize n
|}
The following instructions deliver what is required:
27 SYRAQ SIZE
1 SYR5K … SYR5K [20 times] DROP SyMax RCL
{{out}}
<pre>
2: 127
1: 77031
</pre>
=={{header|Ruby}}==
This program uses new methods (Integer#even? and Enumerable#max_by) from Ruby 1.8.7.
{{works with|Ruby|1.8.7}}
<langsyntaxhighlight lang="ruby">def hailstone n
seq = [n]
until n == 1
Line 6,436 ⟶ 9,221:
n = (1 ... 100_000).max_by{|n| hailstone(n).length}
puts "#{n} has a hailstone sequence length of #{hailstone(n).length}"
puts "the largest number in that sequence is #{hailstone(n).max}"</langsyntaxhighlight>
{{out}}
<pre>
Line 6,450 ⟶ 9,235:
This avoids recomputing the end of the sequence.
{{works with|Ruby|1.8.7}}
<langsyntaxhighlight lang="ruby">module Hailstone
ListNode = Struct.new(:value, :size, :succ) do
def each
Line 6,487 ⟶ 9,272:
n = (1 ... 100_000).max_by{|n| Hailstone.sequence(n).size}
puts "#{n} has a hailstone sequence length of #{Hailstone.sequence(n).size}"
puts "the largest number in that sequence is #{Hailstone.sequence(n).max}"</langsyntaxhighlight>
output is the same as the above.
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn hailstone(start : u32) -> Vec<u32> {
let mut res = Vec::new();
let mut next = start;
Line 6,530 ⟶ 9,315:
}
println!("Longest sequence is {} element long for seed {}", max_len, max_seed);
}</langsyntaxhighlight>
{{out}}
<pre>For 27 number of elements is 112
hailstone starting with 27, 82, 41, 124, ending with 8, 4, 2, 1,
Longest sequence is 351 element long for seed 77031</pre>
 
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">% lst=1, return list of elements; lst=0 just return length
define hailstone(n, lst)
{
Line 6,582 ⟶ 9,366:
}
}
() = printf("\n");</langsyntaxhighlight>
{{out}}
<pre>Hailstone(27) has 112 elements starting with:
Line 6,591 ⟶ 9,375:
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
* Create a routine to generate the hailstone sequence for one number;
%macro gen_seq(n);
Line 6,646 ⟶ 9,430:
%mend;
%longest_hailstone(1,99999);
</syntaxhighlight>
</lang>
 
{{out}}
Line 6,660 ⟶ 9,444:
start sequence
77031 351
</pre>
 
=={{header|S-BASIC}}==
<syntaxhighlight lang="s-basic">comment
Compute and display "hailstone" (i.e., Collatz) sequence
for a given number and find the longest sequence in the
range permitted by S-BASIC's 16-bit integer data type.
end
 
$lines
 
$constant false = 0
$constant true = FFFFH
 
rem - compute p mod q
function mod(p, q = integer) = integer
end = p - q * (p/q)
 
comment
Compute, and optionally display, hailstone sequence for n.
Return length of sequence or zero on overflow
end
function hailstone(n, display = integer) = integer
var length = integer
length = 1
while (n <> 1) and (n > 0) do
begin
if display then print using "##### ", n;
if mod(n,2) = 0 then
n = n / 2
else
n = (n * 3) + 1
length = length + 1
end
if display then print using "##### ", n
rem - return 0 on overflow
if n < 0 then length = 0
end = length
 
var n, limit, slen, longest, n_longest = integer
 
input "Display hailstone sequence for what number"; n
slen = hailstone(n, true)
print "Sequence length = "; slen
 
rem - find longest sequence before overflow
n = 2
longest = 1
slen = 1
limit = 1000;
print "Searching for longest sequence up to N =", limit," ..."
while (n < limit) and (slen <> 0) do
begin
slen = hailstone(n, false)
if slen > longest then
begin
longest = slen
n_longest = n
end
n = n + 1
end
if slen = 0 then print "Search terminated with overflow at";n-1
print "Maximum sequence length =";longest;" for N =";n_longest
 
end
</syntaxhighlight>
{{out}}
<pre>Display hailstone sequence for what number? 27
27 82 41 124 62 31 94 47 142 71
214 107 322 161 484 242 121 364 182 91
274 137 412 206 103 310 155 466 233 700
350 175 526 263 790 395 1186 593 1780 890
445 1336 668 334 167 502 251 754 377 1132
566 283 850 425 1276 638 319 958 479 1438
719 2158 1079 3238 1619 4858 2429 7288 3644 1822
911 2734 1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325 976 488
244 122 61 184 92 46 23 70 35 106
53 160 80 40 20 10 5 16 8 4
2 1
Sequence length = 112
Searching for longest sequence up to N = 1000 ...
Search terminated with overflow at 447
Maximum sequence length = 144 for N = 327
</pre>
 
Line 6,665 ⟶ 9,533:
{{libheader|Scala}}
{{works with|Scala|2.10.2}}
<langsyntaxhighlight Scalalang="scala">object HailstoneSequence extends App {
def hailstone(n: Int): Stream[Int] =
n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))
Line 6,679 ⟶ 9,547:
val (n, len) = (1 until 100000).map(n => (n, hailstone(n).length)).maxBy(_._2)
println(s"Longest hailstone sequence length= $len occurring with number $n.")
}</langsyntaxhighlight>
{{Out}}
<pre>Use the routine to show that the hailstone sequence for the number: 27.
Line 6,689 ⟶ 9,557:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (collatz n)
(if (= n 1) '(1)
(cons n (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n)))))))
Line 6,716 ⟶ 9,584:
 
(collatz-max 1 100000)
; (77031 351)</langsyntaxhighlight>
 
=={{header|Scilab}}==
{{trans|MATLAB}}
<syntaxhighlight lang="text">function x=hailstone(n)
// iterative definition
// usage: global verbose; verbose=%T; hailstone(27)
Line 6,752 ⟶ 9,620:
M(k)=hailstone(k);
end;
[maxLength,n]=max(M)</langsyntaxhighlight>
{{out}}
<pre>27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
Line 6,760 ⟶ 9,628:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array integer: hailstone (in var integer: n) is func
Line 6,817 ⟶ 9,685:
writeln(" length=" <& length(h27));
writeln("Maximum length " <& maxLength <& " at number=" <& numberOfMaxLength);
end func;</langsyntaxhighlight>
 
{{out}}
Line 6,825 ⟶ 9,693:
Maximum length 351 at number=77031
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program hailstone_sequence;
hail27 := hailstone(27);
print("The hailstone sequence for the number 27 has", #hail27, "elements,");
print("starting with", hail27(..4), "and ending with", hail27(#hail27-3..));
 
sizes := [#hailstone(n) : n in [1..99999]];
maxsize := max/sizes;
maxelem := [n : n in [1..#sizes] | sizes(n) = maxsize](1);
 
print("The number < 100,000 with the longest hailstone sequence is",maxelem);
print("The length of its sequence is",sizes(maxelem));
 
proc hailstone(n);
seq := [];
loop doing seq with:= n; while n/=1 do
if even n then
n div:= 2;
else
n := 3*n + 1;
end if;
end loop;
return seq;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>The hailstone sequence for the number 27 has 112 elements,
starting with [27 82 41 124] and ending with [8 4 2 1]
The number < 100,000 with the longest hailstone sequence is 77031
The length of its sequence is 351</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func hailstone (n) {
var sequence = [n]
while (n > 1) {
Line 6,850 ⟶ 9,749:
}
 
printf("%d: (%d)\n", h...)</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Object subclass: Sequences [
Sequences class >> hailstone: n [
|seq|
Line 6,876 ⟶ 9,775:
ifFalse: [ ^ Sequences hailstoneCount: ( (3*n) + 1) num: (m + 1) ].
]
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">|r|
r := Sequences hailstone: 27. "hailstone 'from' 27"
(r size) displayNl. "its length"
Line 6,897 ⟶ 9,796:
 
('Sequence generator %1, sequence length %2' % { (longest at: 1) . (longest at: 2) })
displayNl.</langsyntaxhighlight>
 
=={{header|SNUSP}}==
Line 6,910 ⟶ 9,809:
\+<-/!< ----------.++++++++++/ # +/! +/! +/! +/! +/
</pre>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
<lang Swift>
func hailstone(var n:Int) -> [Int] {
 
Line 6,945 ⟶ 9,845:
}
 
println("Longest sequence for numbers under 100,000 is with \(longest.n). Which has \(longest.len) items.")</langsyntaxhighlight>
{{out}}
<pre>
Line 6,954 ⟶ 9,854:
=={{header|Tcl}}==
The core looping structure is an example of an [[Loops/N plus one half|n-plus-one-half loop]], except the loop is officially infinite here.
<langsyntaxhighlight lang="tcl">proc hailstone n {
while 1 {
lappend seq $n
Line 6,972 ⟶ 9,872:
if {$l>$maxlen} {set maxlen $l;set max $i}
}
puts "max is $max, with length $maxlen"</langsyntaxhighlight>
 
{{out}}
Line 6,984 ⟶ 9,884:
=={{header|TI-83 BASIC}}==
===Task 1===
<langsyntaxhighlight lang="ti83b">prompt N
N→M: 0→X: 1→L
While L=1
Line 6,998 ⟶ 9,898:
End
End
{N,X}</langsyntaxhighlight>
{{out}}
<pre> 10
Line 7,010 ⟶ 9,910:
===Task 2===
As the calculator is quite slow, so the output is for N=200
<langsyntaxhighlight lang="ti83b">prompt N
0→A:0→B
for(I,1,N)
Line 7,030 ⟶ 9,930:
Disp {I,X}
End
{A,B}</langsyntaxhighlight>
{{out}}
<pre>{171,125}</pre>
 
=={{header|Transd}}==
{{trans|Python}}
<syntaxhighlight lang="scheme">#lang transd
 
MainModule: {
hailstone: (λ n Int()
(with seq Vector<Int>([n])
(while (> n 1)
(= n (if (mod n 2) (+ (* 3 n) 1)
else (/ n 2)))
(append seq n)
)
(ret seq)
)
),
 
_start: (λ
(with h (hailstone 27) l 0 n 0 t 0
(lout "Length of (27): " (size h))
(lout "First 4 of (27): " Range(in: h 0 4))
(lout "Last 4 of (27): " Range(in: h -4 -0))
(for i in Range(100000) do
(= t (size (hailstone (to-Int i)))) (if (> t l) (= l t) (= n i))
)
(lout "For n < 100.000 the max. sequence length is " l " for " n)
)
)
}</syntaxhighlight>{{out}}
<pre>
Length of (27): 112
First 4 of (27): [27, 82, 41, 124]
Last 4 of (27): [8, 4, 2, 1]
For n < 100.000 the max. sequence length is 351 for 77031
</pre>
 
=={{header|TXR}}==
<langsyntaxhighlight lang="txr">@(do (defun hailstone (n)
(cons n
(gen (not (eq n 1))
Line 7,060 ⟶ 9,995:
(set max len)
(set maxi i))))
(format t "longest sequence is ~a for n = ~a\n" max maxi)))</langsyntaxhighlight>
 
<pre>$ txr -l hailstone.txr
Line 7,067 ⟶ 10,002:
=={{header|uBasic/4tH}}==
{{Trans|FreeBASIC}}
<syntaxhighlight lang="text">' ------=< MAIN >=------
 
m = 0
Line 7,135 ⟶ 10,070:
Loop
 
Return (b@)</langsyntaxhighlight>
uBasic is an interpreted language. Doing a sequence up to 100,000 would take over an hour, so we did up to 10,000 here.
{{out}}<pre>sequence for number 27
Line 7,161 ⟶ 10,096:
The best way is to use a shell with built-in arrays and arithmetic, such as Bash.
{{works with|Bash}}
<langsyntaxhighlight lang="bash">#!/bin/bash
# seq is the array genereated by hailstone
# index is used for seq
Line 7,197 ⟶ 10,132:
done
 
echo "${max} has a hailstone sequence length of ${maxlen}"</langsyntaxhighlight>
 
{{out}}
Line 7,212 ⟶ 10,147:
 
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash"># Outputs a hailstone sequence from $1, with one element per line.
# Clobbers $n.
hailstone() {
Line 7,241 ⟶ 10,176:
i=`expr $i + 1`
done
echo "Hailstone sequence from $max has $maxlen elements."</langsyntaxhighlight>
 
==={{header|C Shell}}===
Line 7,247 ⟶ 10,182:
This script is '''slow''', but it can reach 100000, and a fast computer might run it in less than 15 minutes.
 
<langsyntaxhighlight lang="csh"># Outputs a hailstone sequence from !:1, with one element per line.
# Clobbers $n.
alias hailstone eval \''@ n = \!:1:q \\
Line 7,297 ⟶ 10,232:
@ i += 1
end
echo "Hailstone sequence from $max has $maxlen elements."</langsyntaxhighlight>
 
{{out}}
Line 7,308 ⟶ 10,243:
===Implementation===
<b>hailstone.u</b>
<langsyntaxhighlight lang="ursa">import "math"
 
def hailstone (int n)
Line 7,322 ⟶ 10,257:
append n seq
return seq
end hailstone</langsyntaxhighlight>
 
===Usage===
Line 7,346 ⟶ 10,281:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 7,357 ⟶ 10,292:
<
^T(@ixX take/$4; %nLP~~lrxPX; ^|TL/~& :/'...',' has length '--@h+ %nP+ length) hail 27,
^|TL(~&,:/' has sequence length ') %nP~~ nleq$^&r ^(~&,length+ hail)* nrange/1 100000></langsyntaxhighlight>
The <code>hail</code> function computes the sequence as follows.
* Given a number as an argument, <code>@iNC</code> makes a list containing only that number before passing it to the rest of the function. The <code>i</code> in the expression stands for the identity function, <code>N</code> for the constant null function, and <code>C</code> for the cons operator.
Line 7,378 ⟶ 10,313:
<pre><27,82,41,124>...<8,4,2,1> has length 112
77031 has sequence length 351</pre>
 
=={{header|VBA}}==
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function hailstone(ByVal n As Long) As Collection
Dim s As New Collection
s.Add CStr(n), CStr(n)
i = 0
Do While n <> 1
If n Mod 2 = 0 Then
n = n / 2
Else
n = 3 * n + 1
End If
s.Add CStr(n), CStr(n)
Loop
Set hailstone = s
End Function
Private Function hailstone_count(ByVal n As Long)
Dim count As Long: count = 1
Do While n <> 1
If n Mod 2 = 0 Then
n = n / 2
Else
n = 3 * n + 1
End If
count = count + 1
Loop
hailstone_count = count
End Function
Public Sub rosetta()
Dim s As Collection, i As Long
Set s = hailstone(27)
Dim ls As Integer: ls = s.count
Debug.Print "hailstone(27) = ";
For i = 1 To 4
Debug.Print s(i); ", ";
Next i
Debug.Print "... ";
For i = s.count - 4 To s.count - 1
Debug.Print s(i); ", ";
Next i
Debug.Print s(s.count)
Debug.Print "length ="; ls
Dim hmax As Long: hmax = 1
Dim imax As Long: imax = 1
Dim count As Integer
For i = 2 To 100000# - 1
count = hailstone_count(i)
If count > hmax Then
hmax = count
imax = i
End If
Next i
Debug.Print "The longest hailstone sequence under 100,000 is"; imax; "with"; hmax; "elements."
End Sub</syntaxhighlight>{{out}}<pre>hailstone(27) = 27, 82, 41, 124, ... 16, 8, 4, 2, 1
length = 112
The longest hailstone sequence under 100,000 is 77031 with 351 elements.</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'function arguments: "num" is the number to sequence and "return" is the value to return - "s" for the sequence or
'"e" for the number elements.
Line 7,423 ⟶ 10,416:
WScript.StdOut.WriteLine "Number less than 100k with the longest sequence: "
WScript.StdOut.WriteLine n_longest
</syntaxhighlight>
</lang>
 
{{Out}}
Line 7,437 ⟶ 10,430:
{{trans|PL/I}}
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">Option Explicit
Dim flag As Boolean ' true to print values
Sub main()
Line 7,493 ⟶ 10,486:
End If
hailstones = p
End Function 'hailstones</langsyntaxhighlight>
{{Out}}
<pre>The sequence for 27 is: 27 82 41 124 ... 8 4 2 1
Line 7,501 ⟶ 10,494:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2005+}}
<langsyntaxhighlight lang="vbnet">Module HailstoneSequence
Sub Main()
' Checking sequence of 27.
Line 7,542 ⟶ 10,535:
End Function
 
End Module</langsyntaxhighlight>
 
{{out}}
Line 7,548 ⟶ 10,541:
27, 82, 41, 124, ... , 8, 4, 2, 1
Max elements in sequence for number below 100k: 77031 with 351 elements.
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">// 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
fn hs(nn int, recycle []int) []int {
mut n := nn
mut s := recycle[..0]
s << n
for n > 1 {
if n&1 == 0 {
n /= 2
} else {
n = 3*n + 1
}
s << n
}
return s
}
fn main() {
mut seq := hs(27, [])
println("hs(27): $seq.len elements: [${seq[0]} ${seq[1]} ${seq[2]} ${seq[3]} ... ${seq[seq.len-4]} ${seq[seq.len-3]} ${seq[seq.len-2]} ${seq[seq.len-1]}]")
mut max_n, mut max_len := 0,0
for n in 1..100000 {
seq = hs(n, seq)
if seq.len > max_len {
max_n = n
max_len = seq.len
}
}
println("hs($max_n): $max_len elements")
}</syntaxhighlight>
{{out}}
<pre>hs(27): 112 elements: [27 82 41 124 ... 8 4 2 1]
hs(77031): 351 elements</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var hailstone = Fn.new { |n|
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
var h = [n]
while (n != 1) {
n = (n%2 == 0) ? (n/2).floor : 3*n + 1
h.add(n)
}
return h
}
 
var h = hailstone.call(27)
System.print("For the Hailstone sequence starting with n = 27:")
System.print(" Number of elements = %(h.count)")
System.print(" First four elements = %(h[0..3])")
System.print(" Final four elements = %(h[-4..-1])")
 
System.print("\nThe Hailstone sequence for n < 100,000 with the longest length is:")
var longest = 0
var longlen = 0
for (n in 1..99999) {
var h = hailstone.call(n)
var c = h.count
if (c > longlen) {
longest = n
longlen = c
}
}
System.print(" Longest = %(longest)")
System.print(" Length = %(longlen)")</syntaxhighlight>
 
{{out}}
<pre>
For the Hailstone sequence starting with n = 27:
Number of elements = 112
First four elements = [27, 82, 41, 124]
Final four elements = [8, 4, 2, 1]
 
The Hailstone sequence for n < 100,000 with the longest length is:
Longest = 77031
Length = 351
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int Seq(1000); \more than enough for longest sequence
 
Line 7,580 ⟶ 10,653:
];
IntOut(0, SN); Text(0, "'s Hailstone length = "); IntOut(0, MaxLen);
]</langsyntaxhighlight>
 
{{out}}
Line 7,587 ⟶ 10,660:
Sequence = 27 82 41 124 ... 8 4 2 1
77031's Hailstone length = 351
</pre>
 
=={{header|Z80 Assembly}}==
This task will be split into two parts, in order to fit all the output of each on one Amstrad CPC screen.
===Show The Sequence with n=27===
Output is in hexadecimal but is otherwise correct.
<syntaxhighlight lang="z80">;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
read "\SrcALL\winapeBuildCompat.asm"
;;;;;;;;;;;;;;;;;;; PROGRAM ;;;;;;;;;;;;;;;;;;;
 
org &8000
ld de,27
call doHailstone
;returns length of sequence, and writes each entry in the sequence
; to RAM
 
;print the sequence length (in hex)
ld a,h
call ShowHex
ld a,l
ld (memdump_smc),a
;just to prove I didn't need to know the sequence length at
; compile time, I'll store the calculated length as the operand
; of "doMemDump" which normally takes a constant embedded after
; it as the number of bytes to display.
 
; If that doesn't make sense, don't worry.
; This has nothing to do with calculating the hailstone sequence, just showing the results.
call ShowHex
 
call NewLine ;prints CRLF
call NewLine
 
call doMemDump
memdump_smc:
byte 0 ;operand of "doMemDump" (gets overwritten with the sequence length)
word HailstoneBuffer ;operand of "doMemDump"
 
 
ret
 
;;;;;;;;;;;;;;;;;;; LIBRARY ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_stringop.asm"
read "\SrcCPC\winape_showhex.asm"
 
 
doHailstone:
;you need the proper input for the function "hailstone"
;returns addr. of last element in IX.
call hailstone
ld de,HailstoneBuffer
or a ;clear carry
push ix
pop hl ;returns element count in HL.
sbc hl,de ;subtract the two to get the length of the array.
 
SRL H
RR L ;divide array size by 2, since each entry is 2 bytes.
INC L
ret nz ;if no carry, don't increment H.
INC H
ret
 
 
hailstone:
;input - de = n
ld ix,HailstoneBuffer
ld a,d
or e
ret z ;zero is not allowed.
loop_hailstone:
ld (IX+0),e
ld (IX+1),d
ld a,e
cp 1
jr nz,continue_hailstone
ld a,d
or a
ret z ;if de = 1, stop.
continue_hailstone:
bit 0,e
jr z,DE_IS_EVEN
;de is odd
push de
pop hl ;ld hl,de
 
SLA E
RL D
add hl,de ;hl = de*3
 
ld de,1
add hl,de
 
push hl
pop de ;ld de,hl
 
inc ix
inc ix
jr loop_hailstone
 
DE_IS_EVEN:
SRL D ;A/2
RR E
inc ix
inc ix
jr loop_hailstone
 
 
doMemDump:
;show the hailstone sequence to the screen. This is just needed to display the data, if you don't care about that
;you can stop reading here.
pop hl ;get PC
ld b,(hl) ;get byte count
inc hl
ld e,(hl) ;get low byte of start addr.
inc hl
ld d,(hl) ;get high byte of start addr.
inc hl
push hl ;now when we return we'll skip the data block.
ex de,hl
 
 
call NewLine
 
;we'll dump 8 words per line.
 
ld c,8
loop_doMemDump:
inc hl
ld a,(hl)
call ShowHex
dec hl
ld a,(hl)
call ShowHex
ld a,' '
call PrintChar
inc hl
inc hl
dec c
ld a,c
and %00001111
jr nz,continueMemdump
ld c,8
continueMemdump:
djnz loop_doMemDump
ret
 
 
 
HailstoneBuffer:
ds 512,0</syntaxhighlight>
 
{{out}}
<pre>
call &8000
0070
 
001B 0052 0029 007C 003E 001F 005E 002F
008E 0047 00D6 006B 0142 00A1 01E4 00F2
0079 016C 00B6 005B 0112 0089 019C 00CE
0067 0136 009B 01D2 00E9 02BC 015E 00AF
01BD 0538 029C 014E 00A7 01F6 00FB 02F2
0179 046C 0236 011B 0352 01A9 04FC 027E
013F 03BE 01DF 059E 02CF 086E 0437 0CA6
0653 12FA 097D 1C78 0E3C 071E 038F 0AAE
0557 1006 0803 180A 0C05 2410 1208 0904
0482 0241 06C4 0362 01B1 0514 028A 0145
03D0 01E8 00F4 007A 003D 00B8 005C 002E
0017 0046 0023 006A 0035 00A0 0050 0028
0014 000A 0005 0010 0008 0004 0002 0001
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z);
if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,z)) }</langsyntaxhighlight>
This uses tail recursion and thus is stack efficient.
{{out}}
Line 7,604 ⟶ 10,849:
</pre>
Rather than write a function that calculates the length, just roll through all 100,000 sequences and save the largest (length,sequence start) pair. Creating all those Collatz lists isn't quick. This works by using a [mutable] list to hold state as the pump does the basic looping.
<langsyntaxhighlight lang="zkl">[2..0d100_000].pump(Void, // loop n from 2 to 100,000
collatz, // generate Collatz sequence(n)
fcn(c,n){ // if new longest sequence, save length/C, return longest
if(c.len()>n[0]) n.clear(c.len(),c[0]); n}.fp1(L(0,0)))</langsyntaxhighlight>
{{out}}
<pre>
Line 7,615 ⟶ 10,860:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET n=27: LET s=1
20 GO SUB 1000
30 PRINT '"Sequence length = ";seqlen
Line 7,635 ⟶ 10,880:
1060 LET l=l+1
1070 GO TO 1020
2000 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
2,114

edits