Hailstone sequence: Difference between revisions

Content added Content deleted
No edit summary
m (syntax highlighting fixup automation)
Line 39: Line 39:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F hailstone(=n)
<syntaxhighlight lang="11l">F hailstone(=n)
V seq = [n]
V seq = [n]
L n > 1
L n > 1
Line 50: Line 50:


V m = max((1..99999).map(i -> (hailstone(i).len, i)))
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]))</lang>
print(‘Maximum length #. was found for hailstone(#.) for numbers <100,000’.format(m[0], m[1]))</syntaxhighlight>


{{out}}
{{out}}
Line 58: Line 58:


=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
<lang 360asm>* Hailstone sequence 16/08/2015
<syntaxhighlight lang="360asm">* Hailstone sequence 16/08/2015
HAILSTON CSECT
HAILSTON CSECT
USING HAILSTON,R12
USING HAILSTON,R12
Line 160: Line 160:
XDEC DS CL12
XDEC DS CL12
YREGS
YREGS
END HAILSTON</lang>
END HAILSTON</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 168: Line 168:


=={{header|ABAP}}==
=={{header|ABAP}}==
<syntaxhighlight lang="abap">
<lang ABAP>
CLASS lcl_hailstone DEFINITION.
CLASS lcl_hailstone DEFINITION.
PUBLIC SECTION.
PUBLIC SECTION.
Line 258: Line 258:
cl_demo_output=>write( lcl_hailstone=>get_longest_sequence_upto( 100000 ) ).
cl_demo_output=>write( lcl_hailstone=>get_longest_sequence_upto( 100000 ) ).
cl_demo_output=>display( ).
cl_demo_output=>display( ).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 276: Line 276:


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun hailstone (len)
<syntaxhighlight lang="lisp">(defun hailstone (len)
(loop for x = len
(loop for x = len
then (if (evenp x)
then (if (evenp x)
Line 291: Line 291:
(if (> new-mx mx)
(if (> new-mx mx)
(max-hailstone-start (1- limit) new-mx limit)
(max-hailstone-start (1- limit) new-mx limit)
(max-hailstone-start (1- limit) mx curr)))))</lang>
(max-hailstone-start (1- limit) mx curr)))))</syntaxhighlight>


{{out}}
{{out}}
Line 305: Line 305:
=={{header|Ada}}==
=={{header|Ada}}==
Similar to [[#C|C method]]:
Similar to [[#C|C method]]:
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure hailstone is
procedure hailstone is
type int_arr is array(Positive range <>) of Integer;
type int_arr is array(Positive range <>) of Integer;
Line 343: Line 343:
end loop;
end loop;
put_line(Integer'Image(nmax)&" max @ n= "&Integer'Image(stonemax));
put_line(Integer'Image(nmax)&" max @ n= "&Integer'Image(stonemax));
end hailstone;</lang>
end hailstone;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 355: Line 355:


hailstones.ads:
hailstones.ads:
<lang Ada>package Hailstones is
<syntaxhighlight lang="ada">package Hailstones is
type Integer_Sequence is array(Positive range <>) of Integer;
type Integer_Sequence is array(Positive range <>) of Integer;
function Create_Sequence (N : Positive) return Integer_Sequence;
function Create_Sequence (N : Positive) return Integer_Sequence;
end Hailstones;</lang>
end Hailstones;</syntaxhighlight>
hailstones.adb:
hailstones.adb:
<lang Ada>package body Hailstones is
<syntaxhighlight lang="ada">package body Hailstones is
function Create_Sequence (N : Positive) return Integer_Sequence is
function Create_Sequence (N : Positive) return Integer_Sequence is
begin
begin
Line 374: Line 374:
end if;
end if;
end Create_Sequence;
end Create_Sequence;
end Hailstones;</lang>
end Hailstones;</syntaxhighlight>
example main.adb:
example main.adb:
<lang Ada>with Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO;
with Hailstones;
with Hailstones;


Line 418: Line 418:
Ada.Text_IO.Put_Line ("with N =" & Integer'Image (Longest_N));
Ada.Text_IO.Put_Line ("with N =" & Integer'Image (Longest_N));
end;
end;
end Main;</lang>
end Main;</syntaxhighlight>
{{out}}
{{out}}
<pre>Length of 27: 112
<pre>Length of 27: 112
Line 427: Line 427:


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang="aime">void
print_hailstone(integer h)
print_hailstone(integer h)
{
{
Line 484: Line 484:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>hailstone sequence for 27 is 27 82 41 124 .. 8 4 2 1, it is 112 long
<pre>hailstone sequence for 27 is 27 82 41 124 .. 8 4 2 1, it is 112 long
Line 491: Line 491:
=={{header|ALGOL 60}}==
=={{header|ALGOL 60}}==
{{works with|A60}}
{{works with|A60}}
<lang algol60>begin
<syntaxhighlight lang="algol60">begin
comment Hailstone sequence - Algol 60;
comment Hailstone sequence - Algol 60;
integer array collatz[1:400]; integer icollatz;
integer array collatz[1:400]; integer icollatz;
Line 533: Line 533:
outstring(1,", with"); outinteger(1,nel); outstring(1,"elements.");
outstring(1,", with"); outinteger(1,nel); outstring(1,"elements.");
outstring(1,"\n")
outstring(1,"\n")
end </lang>
end </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 549: Line 549:
{{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|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''}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - using the ''print'' routine rather than ''printf''}}
<lang algol68>MODE LINT = # LONG ... # INT;
<syntaxhighlight lang="algol68">MODE LINT = # LONG ... # INT;


PROC hailstone = (INT in n, REF[]LINT array)INT:
PROC hailstone = (INT in n, REF[]LINT array)INT:
Line 595: Line 595:
print(("Max",hmax," at j=",jatmax, new line))
print(("Max",hmax," at j=",jatmax, new line))
#
#
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 605: Line 605:
=={{header|ALGOL-M}}==
=={{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.
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.
<lang algol>
<syntaxhighlight lang="algol">
BEGIN
BEGIN


Line 665: Line 665:
WRITE("MAXIMUM SEQUENCE LENGTH =", LONGEST, " FOR N =", NLONG);
WRITE("MAXIMUM SEQUENCE LENGTH =", LONGEST, " FOR N =", NLONG);


END </lang>
END </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 688: Line 688:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% show some Hailstone Sequence related information %
% show some Hailstone Sequence related information %
% calculates the length of the sequence generated by n, %
% calculates the length of the sequence generated by n, %
Line 762: Line 762:
end
end
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 771: Line 771:
=={{header|APL}}==
=={{header|APL}}==
{{works with|Dyalog APL}}
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">
<lang APL>
⍝ recursive dfn:
⍝ recursive dfn:
dfnHailstone←{
dfnHailstone←{
Line 791: Line 791:


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang APL> dfnHailstone 5
<syntaxhighlight lang="apl"> dfnHailstone 5
5 16 8 4 2 1
5 16 8 4 2 1
5↑hailstone 27
5↑hailstone 27
Line 802: Line 802:
112
112
1↑{⍵[⍒↑(⍴∘hailstone)¨⍵]}⍳100000
1↑{⍵[⍒↑(⍴∘hailstone)¨⍵]}⍳100000
77031</lang>
77031</syntaxhighlight>


=={{header|AppleScript}}==
=={{header|AppleScript}}==


<lang applescript>on hailstoneSequence(n)
<syntaxhighlight lang="applescript">on hailstoneSequence(n)
script o
script o
property sequence : {n}
property sequence : {n}
Line 826: Line 826:
tell hailstoneSequence(n)
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}
return {n:n, |length of sequence|:(its length), |first 4 numbers|:items 1 thru 4, |last 4 numbers|:items -4 thru -1}
end tell</lang>
end tell</syntaxhighlight>


{{output}}
{{output}}
<pre>{|length of sequence|:112, |first 4 numbers|:{27, 82, 41, 124}, |last 4 numbers|:{8, 4, 2, 1}}</pre>
<pre>{|length of sequence|:112, |first 4 numbers|:{27, 82, 41, 124}, |last 4 numbers|:{8, 4, 2, 1}}</pre>


<lang applescript>-- Number(s) below 100,000 giving the longest sequence length, using the hailstoneSequence(n) handler above.
<syntaxhighlight lang="applescript">-- Number(s) below 100,000 giving the longest sequence length, using the hailstoneSequence(n) handler above.
set nums to {}
set nums to {}
set longestLength to 1
set longestLength to 1
Line 843: Line 843:
set end of nums to n
set end of nums to n
end if
end if
end repeat</lang>
end repeat</syntaxhighlight>


{{output}}
{{output}}
Line 855: Line 855:
===Hailstone Sequence of N equal to 27 ===
===Hailstone Sequence of N equal to 27 ===


<lang ARM Assembly> .org 0x08000000
<syntaxhighlight lang="arm assembly"> .org 0x08000000


b ProgramStart
b ProgramStart
Line 1,004: Line 1,004:
;;;;;;;;;;; EVERYTHING PAST THIS POINT IS JUST I/O ROUTINES FOR PRINTING NUMBERS AND WORDS TO THE GAME BOY ADVANCE'S SCREEN
;;;;;;;;;;; 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.
;;;;;;;;;;; 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!</lang>
;;;;;;;;;;; THANKS TO KEITH OF CHIBIAKUMAS.COM FOR WRITING THEM!</syntaxhighlight>


{{out}}
{{out}}
Line 1,033: Line 1,033:
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:
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:


<lang ARM Assembly> mov r0,#1
<syntaxhighlight lang="arm assembly"> mov r0,#1
bl Hailstone
bl Hailstone
mov r6,r3
mov r6,r3
Line 1,071: Line 1,071:
mov r0,r6
mov r0,r6
bl ShowHex32
bl ShowHex32
bl NewLine</lang>
bl NewLine</syntaxhighlight>


{{out}}
{{out}}
Line 1,087: Line 1,087:
=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>hailstone: function [n][
<syntaxhighlight lang="rebol">hailstone: function [n][
ret: @[n]
ret: @[n]
while [n>1][
while [n>1][
Line 1,113: Line 1,113:


print ["max hailstone sequence found (<100000): of length" maxHailstoneLength "for" maxHailstone]
print ["max hailstone sequence found (<100000): of length" maxHailstoneLength "for" maxHailstone]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,123: Line 1,123:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>; Submitted by MasterFocus --- http://tiny.cc/iTunis
<syntaxhighlight lang="autohotkey">; Submitted by MasterFocus --- http://tiny.cc/iTunis


; [1] Generate the Hailstone Seq. for a number
; [1] Generate the Hailstone Seq. for a number
Line 1,162: Line 1,162:
}
}
ToolTip
ToolTip
MsgBox % "Number: " MaxNum "`nCount: " Max</lang>
MsgBox % "Number: " MaxNum "`nCount: " Max</syntaxhighlight>


=={{header|AutoIt}}==
=={{header|AutoIt}}==




<lang autoit>
<syntaxhighlight lang="autoit">
$Hail = Hailstone(27)
$Hail = Hailstone(27)
ConsoleWrite("Sequence-Lenght: "&$Hail&@CRLF)
ConsoleWrite("Sequence-Lenght: "&$Hail&@CRLF)
Line 1,196: Line 1,196:
Return $Counter
Return $Counter
EndFunc ;==>Hailstone
EndFunc ;==>Hailstone
</syntaxhighlight>
</lang>
{{out}}
{{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,
<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 1,208: Line 1,208:


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>
<syntaxhighlight lang="awk">
#!/usr/bin/awk -f
#!/usr/bin/awk -f
function hailstone(v, verbose) {
function hailstone(v, verbose) {
Line 1,238: Line 1,238:
printf("longest hailstone sequence is %i and has %i elements\n",ix,m);
printf("longest hailstone sequence is %i and has %i elements\n",ix,m);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,248: Line 1,248:
=={{header|BASIC}}==
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang ApplesoftBasic>10 HOME
<syntaxhighlight lang="applesoftbasic">10 HOME


100 N = 27
100 N = 27
Line 1,279: Line 1,279:
470 IF EVEN THEN N=N/2
470 IF EVEN THEN N=N/2
480 IF NOT EVEN THEN N = (3 * N) + 1
480 IF NOT EVEN THEN N = (3 * N) + 1
490 NEXT L : STOP</lang>
490 NEXT L : STOP</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> seqlen% = FNhailstone(27, TRUE)
<syntaxhighlight lang="bbcbasic"> seqlen% = FNhailstone(27, TRUE)
PRINT '"Sequence length = "; seqlen%
PRINT '"Sequence length = "; seqlen%
maxlen% = 0
maxlen% = 0
Line 1,304: Line 1,304:
L% += 1
L% += 1
ENDWHILE
ENDWHILE
= L% + 1</lang>
= L% + 1</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,328: Line 1,328:


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang QBASIC>100 PRINT : PRINT "HAILSTONE SEQUENCE FOR N = 27:"
<syntaxhighlight lang="qbasic">100 PRINT : PRINT "HAILSTONE SEQUENCE FOR N = 27:"
110 N=27 : SHOW=1
110 N=27 : SHOW=1
120 GOSUB 1000
120 GOSUB 1000
Line 1,351: Line 1,351:
1060 S = 3*S+1
1060 S = 3*S+1
1070 GOTO 1020
1070 GOTO 1020
</syntaxhighlight>
</lang>
==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang FreeBASIC>' version 17-06-2015
<syntaxhighlight lang="freebasic">' version 17-06-2015
' compile with: fbc -s console
' compile with: fbc -s console


Line 1,443: Line 1,443:
Print : Print : Print "hit any key to end program"
Print : Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{out}}
{{out}}
<pre>sequence for number 27
<pre>sequence for number 27
Line 1,464: Line 1,464:


==={{header|GW-BASIC}}===
==={{header|GW-BASIC}}===
<lang gwbasic>10 N# = 27
<syntaxhighlight lang="gwbasic">10 N# = 27
20 P = 1
20 P = 1
30 GOSUB 130
30 GOSUB 130
Line 1,481: Line 1,481:
160 IF N#/2 = INT(N#/2) THEN N# = N#/2 ELSE N# = 3*N# + 1
160 IF N#/2 = INT(N#/2) THEN N# = N#/2 ELSE N# = 3*N# + 1
170 C = C + 1
170 C = C + 1
180 GOTO 140</lang>
180 GOTO 140</syntaxhighlight>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
<lang lb>print "Part 1: Create a routine to generate the hailstone sequence for a number."
<syntaxhighlight lang="lb">print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
print ""
while hailstone < 1 or hailstone <> int(hailstone)
while hailstone < 1 or hailstone <> int(hailstone)
Line 1,535: Line 1,535:
print ""
print ""
print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"."
print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"."
end</lang>
end</syntaxhighlight>


==={{header|OxygenBasic}}===
==={{header|OxygenBasic}}===
<lang oxygenbasic>
<syntaxhighlight lang="oxygenbasic">


function Hailstone(sys *n)
function Hailstone(sys *n)
Line 1,577: Line 1,577:


'result 100000, 77031, 351
'result 100000, 77031, 351
</syntaxhighlight>
</lang>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
<lang PureBasic>NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array
<syntaxhighlight lang="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
Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list
Line 1,627: Line 1,627:
Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


{{out}}
{{out}}
Line 1,658: Line 1,658:


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
<lang runbasic>print "Part 1: Create a routine to generate the hailstone sequence for a number."
<syntaxhighlight lang="runbasic">print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
print ""
Line 1,697: Line 1,697:
end if
end if
wend
wend
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>


==={{header|Tiny BASIC}}===
==={{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.
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.


<lang> PRINT "Enter a positive integer"
<syntaxhighlight lang="text"> PRINT "Enter a positive integer"
INPUT N REM unit column
INPUT N REM unit column
LET M = 0 REM 32766 column
LET M = 0 REM 32766 column
Line 1,770: Line 1,770:
PRINT "at step number ",C
PRINT "at step number ",C
PRINT "trying to triple 32766x",M," + ",N
PRINT "trying to triple 32766x",M," + ",N
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,793: Line 1,793:
''2. Show that the hailstone sequence for the number 27 has 112 elements... ''
''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...-->
<!--The third task is NOT included because task #3 will take several hours in processing...-->
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
setlocal enabledelayedexpansion
echo.
echo.
Line 1,833: Line 1,833:
set /a num/=2
set /a num/=2
set seq=!seq! %num%
set seq=!seq! %num%
goto loop</lang>
goto loop</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Task #1: (Start:111)
<pre>Task #1: (Start:111)
Line 1,846: Line 1,846:


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.
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.
<lang dos>@echo off
<syntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
setlocal enableDelayedExpansion
if "%~1"=="test" (
if "%~1"=="test" (
Line 1,868: Line 1,868:
pause>nul
pause>nul


exit /b 0</lang>
exit /b 0</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Number less than 100000 with longest sequence: 77031
<pre>Number less than 100000 with longest sequence: 77031
Line 1,879: Line 1,879:
'''The pure hailstone sequence function''', returning the sequence for any number entered in the console:
'''The pure hailstone sequence function''', returning the sequence for any number entered in the console:


<lang beeswax> >@:N q
<syntaxhighlight lang="beeswax"> >@:N q
>%"d3~@.PNp
>%"d3~@.PNp
d~2~pL~1F{<T_</lang>
d~2~pL~1F{<T_</syntaxhighlight>


'''Returning the sequence for the starting value <code>27</code>'''
'''Returning the sequence for the starting value <code>27</code>'''


<lang beeswax> >@:N q
<syntaxhighlight lang="beeswax"> >@:N q
>%"d3~@.PNq
>%"d3~@.PNq
d~2~qL~1Ff{<BF3_
d~2~qL~1Ff{<BF3_
{NNgA<</lang>
{NNgA<</syntaxhighlight>


Output of the sequence, followed by the length of the sequence:
Output of the sequence, followed by the length of the sequence:


<lang>
<syntaxhighlight lang="text">
27
27
82
82
Line 1,922: Line 1,922:
1
1


112</lang>
112</syntaxhighlight>


'''Number below 100,000 with the longest hailstone sequence, and the length of that sequence:'''
'''Number below 100,000 with the longest hailstone sequence, and the length of that sequence:'''


<lang beeswax> >@: q pf1_#
<syntaxhighlight lang="beeswax"> >@: q pf1_#
>%"d3~@.Pqf#{g?` `{gpK@~BP9~5@P@q'M<
>%"d3~@.Pqf#{g?` `{gpK@~BP9~5@P@q'M<
d~2~pL~1Ff< < >?d
d~2~pL~1Ff< < >?d
>zAg?MM@1~y@~gLpz2~yg@~3~hAg?M d
>zAg?MM@1~y@~gLpz2~yg@~3~hAg?M d
>?~fz1~y?yg@hhAg?Mb</lang>
>?~fz1~y?yg@hhAg?Mb</syntaxhighlight>


Output:
Output:


<lang>77031 351</lang>
<syntaxhighlight lang="text">77031 351</syntaxhighlight>


=={{header|Befunge}}==
=={{header|Befunge}}==
<lang befunge>93*:. v
<syntaxhighlight lang="befunge">93*:. v
> :2%v >
> :2%v >
v+1*3_2/
v+1*3_2/
Line 1,955: Line 1,955:
vg01g00 ,+49<
vg01g00 ,+49<
>"@"*+.@
>"@"*+.@
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,965: Line 1,965:
=={{header|BQN}}==
=={{header|BQN}}==
Works in: [[CBQN]]
Works in: [[CBQN]]
<lang bqn>Collatz ← ⥊⊸{
<syntaxhighlight lang="bqn">Collatz ← ⥊⊸{
𝕨𝕊1: 𝕨;
𝕨𝕊1: 𝕨;
(𝕨⊸∾ 𝕊 ⊢) (2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩
(𝕨⊸∾ 𝕊 ⊢) (2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩
Line 1,977: Line 1,977:
•Show Collatz1 5
•Show Collatz1 5


•Show (⊑∾≠){𝕩⊑˜⊑⍒≠¨𝕩}Collatz1¨1+↕99999</lang>
•Show (⊑∾≠){𝕩⊑˜⊑⍒≠¨𝕩}Collatz1¨1+↕99999</syntaxhighlight>
<lang bqn>⟨ 5 16 8 4 2 1 ⟩
<syntaxhighlight lang="bqn">⟨ 5 16 8 4 2 1 ⟩
⟨ 77031 351 ⟩</lang>
⟨ 77031 351 ⟩</syntaxhighlight>


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>(
<syntaxhighlight lang="bracmat">(
( hailstone
( hailstone
= L len
= L len
Line 2,024: Line 2,024:
)
)
)
)
);</lang>
);</syntaxhighlight>


=={{header|Brainf***}}==
=={{header|Brainf***}}==
{{incomplete}}
{{incomplete}}
<lang Brainf***>>>>>>>,>,>,<<
<syntaxhighlight lang="brainf***">>>>>>>,>,>,<<


[
[
Line 2,110: Line 2,110:
[Cell 16: ASCII code for " " (Space). ]
[Cell 16: ASCII code for " " (Space). ]
[Rest of the cells: Temp cells. ]
[Rest of the cells: Temp cells. ]
</syntaxhighlight>
</lang>


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>hailstone = { num |
<syntaxhighlight lang="brat">hailstone = { num |
sequence = [num]
sequence = [num]
while { num != 1 }
while { num != 1 }
Line 2,145: Line 2,145:
}
}


p "Longest was starting from #{longest[:number]} and was of length #{longest[:length]}"</lang>
p "Longest was starting from #{longest[:number]} and was of length #{longest[:length]}"</syntaxhighlight>
{{out}}
{{out}}
<pre>Sequence for 27 is correct
<pre>Sequence for 27 is correct
Line 2,158: Line 2,158:
=={{header|Burlesque}}==
=={{header|Burlesque}}==


<lang burlesque>
<syntaxhighlight lang="burlesque">
blsq ) 27{^^^^2.%{3.*1.+}\/{2./}\/ie}{1!=}w!bx{\/+]}{\/isn!}w!L[
blsq ) 27{^^^^2.%{3.*1.+}\/{2./}\/ie}{1!=}w!bx{\/+]}{\/isn!}w!L[
112
112
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>


Line 2,204: Line 2,204:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[ 27, 82, 41, 124, ...., 8, 4, 2, 1] len= 112
<pre>[ 27, 82, 41, 124, ...., 8, 4, 2, 1] len= 112
Line 2,211: Line 2,211:
===With caching===
===With caching===
Much faster if you want to go over a million or so.
Much faster if you want to go over a million or so.
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>


#define N 10000000
#define N 10000000
Line 2,241: Line 2,241:
printf("max below %d: %d, length %d\n", N, mi, max);
printf("max below %d: %d, length %d\n", N, mi, max);
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Linq;
Line 2,287: Line 2,287:
}
}
}
}
}</lang>
}</syntaxhighlight>
<pre>
<pre>
112 Elements
112 Elements
Line 2,296: Line 2,296:
===With caching===
===With caching===
As with the [[#C|C example]], much faster if you want to go over a million or so.
As with the [[#C|C example]], much faster if you want to go over a million or so.
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Collections.Generic;


Line 2,337: Line 2,337:
}
}
}
}
}</lang>
}</syntaxhighlight>
<pre>
<pre>
max below 100000: 77031 (351 steps)
max below 100000: 77031 (351 steps)
Line 2,343: Line 2,343:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
#include <vector>
#include <vector>
#include <utility>
#include <utility>
Line 2,392: Line 2,392:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,404: Line 2,404:
{{uses from|library|Qt}}
{{uses from|library|Qt}}
Templated solution works for all of Qt's sequential container classes (QLinkedList, QList, QVector).
Templated solution works for all of Qt's sequential container classes (QLinkedList, QList, QVector).
<lang cpp>
<syntaxhighlight lang="cpp">
#include <QDebug>
#include <QDebug>
#include <QVector>
#include <QVector>
Line 2,443: Line 2,443:
qInfo() << " starting element:" << max.first();
qInfo() << " starting element:" << max.first();
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,456: Line 2,456:


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang="ceylon">shared void run() {
{Integer*} hailstone(variable Integer n) {
{Integer*} hailstone(variable Integer n) {
Line 2,478: Line 2,478:
}
}
print("the longest sequence under 100,000 starts with ``longest.first else "what?"`` and has length ``longest.size``");
print("the longest sequence under 100,000 starts with ``longest.first else "what?"`` and has length ``longest.size``");
}</lang>
}</syntaxhighlight>


=={{header|CLIPS}}==
=={{header|CLIPS}}==
<lang clips>(deftemplate longest
<syntaxhighlight lang="clips">(deftemplate longest
(slot bound) ; upper bound for the range of values to check
(slot bound) ; upper bound for the range of values to check
(slot next (default 2)) ; next value that needs to be checked
(slot next (default 2)) ; next value that needs to be checked
Line 2,556: Line 2,556:
(printout t "sequence is " ?start " with a length of " ?len "." crlf)
(printout t "sequence is " ?start " with a length of " ?len "." crlf)
(printout t crlf)
(printout t crlf)
)</lang>
)</syntaxhighlight>


{{out}}
{{out}}
Line 2,568: Line 2,568:


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn hailstone-seq [n]
<syntaxhighlight lang="clojure">(defn hailstone-seq [n]
{:pre [(pos? n)]}
{:pre [(pos? n)]}
(lazy-seq
(lazy-seq
Line 2,584: Line 2,584:
(for [i (range 1 100000)]
(for [i (range 1 100000)]
{:num i, :len (count (hailstone-seq i))}))]
{:num i, :len (count (hailstone-seq i))}))]
(println "Maximum length" max-len "was found for hailstone(" max-i ")."))</lang>
(println "Maximum length" max-len "was found for hailstone(" max-i ")."))</syntaxhighlight>


=={{header|CLU}}==
=={{header|CLU}}==
<lang clu>% Generate the hailstone sequence for a number
<syntaxhighlight lang="clu">% Generate the hailstone sequence for a number
hailstone = iter (n: int) yields (int)
hailstone = iter (n: int) yields (int)
while true do
while true do
Line 2,641: Line 2,641:
|| " has the longest hailstone sequence < 100000: "
|| " has the longest hailstone sequence < 100000: "
|| int$unparse(maxlen))
|| int$unparse(maxlen))
end start_up</lang>
end start_up</syntaxhighlight>
{{out}}
{{out}}
<pre>The hailstone sequence for 27 has 112 elements.
<pre>The hailstone sequence for 27 has 112 elements.
Line 2,649: Line 2,649:
=={{header|COBOL}}==
=={{header|COBOL}}==
Testing with GnuCOBOL
Testing with GnuCOBOL
<lang COBOL> identification division.
<syntaxhighlight lang="cobol"> identification division.
program-id. hailstones.
program-id. hailstones.
remarks. cobc -x hailstones.cob.
remarks. cobc -x hailstones.cob.
Line 2,738: Line 2,738:
.
.


end program hailstones.</lang>
end program hailstones.</syntaxhighlight>


{{out}}
{{out}}
Line 2,753: Line 2,753:
=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
Recursive version:
Recursive version:
<lang coffeescript>hailstone = (n) ->
<syntaxhighlight lang="coffeescript">hailstone = (n) ->
if n is 1
if n is 1
[n]
[n]
Line 2,778: Line 2,778:
maxnums = [i]
maxnums = [i]
console.log "Max length: #{maxlength}; numbers generating sequences of this length: #{maxnums}"</lang>
console.log "Max length: #{maxlength}; numbers generating sequences of this length: #{maxnums}"</syntaxhighlight>
<pre>hailstone(27) = 27,82,41,124 ... 8,4,2,1 (length: 112)
<pre>hailstone(27) = 27,82,41,124 ... 8,4,2,1 (length: 112)
Max length: 351; numbers generating sequences of this length: 77031</pre>
Max length: 351; numbers generating sequences of this length: 77031</pre>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(defun hailstone (n)
<syntaxhighlight lang="lisp">(defun hailstone (n)
(cond ((= n 1) '(1))
(cond ((= n 1) '(1))
((evenp n) (cons n (hailstone (/ n 2))))
((evenp n) (cons n (hailstone (/ n 2))))
Line 2,793: Line 2,793:
(let ((len (length (hailstone i))))
(let ((len (length (hailstone i))))
(when (> len l) (setq l len k 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))))</lang>
finally (format t "Longest hailstone sequence under ~A for ~A, having length ~A." n k l))))</syntaxhighlight>
Sample session:
Sample session:
<pre>ROSETTA> (length (hailstone 27))
<pre>ROSETTA> (length (hailstone 27))
Line 2,806: Line 2,806:


=={{header|Cowgol}}==
=={{header|Cowgol}}==
<lang cowgol>include "cowgol.coh";
<syntaxhighlight lang="cowgol">include "cowgol.coh";


# Generate the hailstone sequence for the given N and return the length.
# Generate the hailstone sequence for the given N and return the length.
Line 2,868: Line 2,868:
print(" has the longest hailstone sequence < 100000: ");
print(" has the longest hailstone sequence < 100000: ");
print_i32(max_len);
print_i32(max_len);
print_nl();</lang>
print_nl();</syntaxhighlight>


{{out}}
{{out}}
Line 2,876: Line 2,876:


=={{header|Crystal}}==
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
def hailstone(n)
def hailstone(n)
seq = [n]
seq = [n]
Line 2,894: Line 2,894:
puts ([twenty_seven.size, twenty_seven.first(4), max.last(4)])
puts ([twenty_seven.size, twenty_seven.first(4), max.last(4)])
# => [112, [27, 82, 41, 124], [8, 4, 2, 1]]
# => [112, [27, 82, 41, 124], [8, 4, 2, 1]]
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
===Basic Version===
===Basic Version===
<lang d>import std.stdio, std.algorithm, std.range, std.typecons;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;


auto hailstone(uint n) pure nothrow {
auto hailstone(uint n) pure nothrow {
Line 2,920: Line 2,920:
.reduce!max;
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>hailstone(27)= [27, 82, 41, 124] ... [8, 4, 2, 1]
<pre>hailstone(27)= [27, 82, 41, 124] ... [8, 4, 2, 1]
Line 2,928: Line 2,928:
===Lazy Version===
===Lazy Version===
Same output.
Same output.
<lang d>import std.stdio, std.algorithm, std.typecons, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.range;


auto hailstone(uint m) pure nothrow @nogc {
auto hailstone(uint m) pure nothrow @nogc {
Line 2,947: Line 2,947:
.reduce!max;
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</lang>
}</syntaxhighlight>


===Faster Lazy Version===
===Faster Lazy Version===
Same output.
Same output.
<lang d>struct Hailstone {
<syntaxhighlight lang="d">struct Hailstone {
uint n;
uint n;
bool empty() const pure nothrow @nogc { return n == 0; }
bool empty() const pure nothrow @nogc { return n == 0; }
Line 2,973: Line 2,973:
.reduce!max;
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</lang>
}</syntaxhighlight>


===Lazy Version With Caching===
===Lazy Version With Caching===
Faster, same output.
Faster, same output.
<lang d>import std.stdio, std.algorithm, std.range, std.typecons;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;


struct Hailstone(size_t cacheSize = 500_000) {
struct Hailstone(size_t cacheSize = 500_000) {
Line 3,009: Line 3,009:
.reduce!max;
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</lang>
}</syntaxhighlight>


===Generator Range Version===
===Generator Range Version===
<lang d>import std.stdio, std.algorithm, std.range, std.typecons, std.concurrency;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons, std.concurrency;


auto hailstone(size_t n) {
auto hailstone(size_t n) {
Line 3,035: Line 3,035:
.reduce!max;
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</lang>
}</syntaxhighlight>


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>List<int> hailstone(int n) {
<syntaxhighlight lang="dart">List<int> hailstone(int n) {
if(n<=0) {
if(n<=0) {
throw new IllegalArgumentException("start value must be >=1)");
throw new IllegalArgumentException("start value must be >=1)");
Line 3,089: Line 3,089:
}
}
print("up to 100000 the sequence h($seq) has the largest length ($max)");
print("up to 100000 the sequence h($seq) has the largest length ($max)");
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>h(1)=[1]
<pre>h(1)=[1]
Line 3,111: Line 3,111:
The e and o procedure is for even and odd number respectively.
The e and o procedure is for even and odd number respectively.
The x procedure is for overall control.
The x procedure is for overall control.
<syntaxhighlight lang="dc">27
<lang Dc>27
[[--: ]nzpq]sq
[[--: ]nzpq]sq
[d 2/ p]se
[d 2/ p]se
[d 3*1+ p]so
[d 3*1+ p]so
[d2% 0=e d1=q d2% 1=o d1=q lxx]dsxx</lang>
[d2% 0=e d1=q d2% 1=o d1=q lxx]dsxx</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,133: Line 3,133:
Register L for the length of the longest sequence and T for the corresponding number.
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.
Also, procedure q is slightly modified for storing L and T if needed, and all printouts in procedure e and o are muted.
<lang Dc>0dsLsT1st
<syntaxhighlight lang="dc">0dsLsT1st
[dsLltsT]sM
[dsLltsT]sM
[[zdlL<M q]sq
[[zdlL<M q]sq
Line 3,141: Line 3,141:
[lt1+dstlsxc lt100000>l]dslx
[lt1+dstlsxc lt100000>l]dslx
lTn[:]nlLp
lTn[:]nlLp
</syntaxhighlight>
</lang>
{{out}} (Takes quite some time on a decent machine)
{{out}} (Takes quite some time on a decent machine)
<pre>77031:351</pre>
<pre>77031:351</pre>


=={{header|DCL}}==
=={{header|DCL}}==
<lang DCL>$ n = f$integer( p1 )
<syntaxhighlight lang="dcl">$ n = f$integer( p1 )
$ i = 1
$ i = 1
$ loop:
$ loop:
Line 3,168: Line 3,168:
$ 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
$ 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
$ endif
$ sequence_length == i</lang>
$ sequence_length == i</syntaxhighlight>
{{out}}
{{out}}
<pre>$ @hailstone 27
<pre>$ @hailstone 27
sequence has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1</pre>
sequence has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1</pre>
<lang DCL>$ limit = f$integer( p1 )
<syntaxhighlight lang="dcl">$ limit = f$integer( p1 )
$ i = 1
$ i = 1
$ max_so_far = 0
$ max_so_far = 0
Line 3,212: Line 3,212:
$ sequence_length == I
$ sequence_length == I
$ exit
$ exit
$ endsubroutine</lang>
$ endsubroutine</syntaxhighlight>
{{out}}
{{out}}
<pre>$ @longest_hailstone 100000
<pre>$ @longest_hailstone 100000
Line 3,221: Line 3,221:
=== Using List<Integer> ===
=== Using List<Integer> ===


<lang Delphi>program ShowHailstoneSequence;
<syntaxhighlight lang="delphi">program ShowHailstoneSequence;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 3,277: Line 3,277:


Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>27: 112 elements
<pre>27: 112 elements
Line 3,292: Line 3,292:
{{libheader| Boost.Int}}[https://github.com/MaiconSoft/DelphiBoostLib]
{{libheader| Boost.Int}}[https://github.com/MaiconSoft/DelphiBoostLib]
{{libheader| System.Diagnostics}}
{{libheader| System.Diagnostics}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program ShowHailstoneSequence;
program ShowHailstoneSequence;


Line 3,345: Line 3,345:
end.
end.


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,356: Line 3,356:


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==
<lang dejavu>local hailstone:
<syntaxhighlight lang="dejavu">local hailstone:
swap [ over ]
swap [ over ]
while < 1 dup:
while < 1 dup:
Line 3,391: Line 3,391:
!print( "number: " to-str max ", length: " to-str maxlen )
!print( "number: " to-str max ", length: " to-str maxlen )
else:
else:
@hailstone</lang>
@hailstone</syntaxhighlight>
{{out}}
{{out}}
<pre>true
<pre>true
Line 3,405: Line 3,405:


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
(lib 'hash)
(lib 'hash)
(lib 'sequences)
(lib 'sequences)
Line 3,435: Line 3,435:
(writeln 'maxlength= hmaxlength 'for hmaxseed))
(writeln 'maxlength= hmaxlength 'for hmaxseed))


</syntaxhighlight>
</lang>
{{out}}
{{out}}
<lang scheme>
<syntaxhighlight lang="scheme">
(define H27 (iterator/f hailstone 27))
(define H27 (iterator/f hailstone 27))
(take H27 6)
(take H27 6)
Line 3,471: Line 3,471:
maxlength= 525 for 837799
maxlength= 525 for 837799


</syntaxhighlight>
</lang>


=={{header|EDSAC order code}}==
=={{header|EDSAC order code}}==
Line 3,477: Line 3,477:
Even with the storage-related code cut out, Part 2 of the task executes 182 million EDSAC orders.
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.
At 650 orders per second, the original EDSAC would have taken 78 hours.
<lang edsac>
<syntaxhighlight lang="edsac">
[Hailstone (or Collatz) task for Rosetta Code.
[Hailstone (or Collatz) task for Rosetta Code.
EDSAC program, Initial Orders 2.]
EDSAC program, Initial Orders 2.]
Line 3,738: Line 3,738:
E 41 Z [define entry point]
E 41 Z [define entry point]
P F [acc = 0 on entry]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,752: Line 3,752:


=={{header|Egel}}==
=={{header|Egel}}==
<syntaxhighlight lang="egel">
<lang Egel>
import "prelude.eg"
import "prelude.eg"


Line 3,795: Line 3,795:


def main = (task0, task1, task2)
def main = (task0, task1, task2)
</syntaxhighlight>
</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 3,866: Line 3,866:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,877: Line 3,877:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x :
ELENA 4.x :
<lang elena>import system'collections;
<syntaxhighlight lang="elena">import system'collections;
import extensions;
import extensions;
Line 3,926: Line 3,926:
console.printFormatted("max below {0}: {1} ({2} steps)", maxNumber, longestNumber, longestChain)
console.printFormatted("max below {0}: {1} ({2} steps)", maxNumber, longestNumber, longestChain)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,933: Line 3,933:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Hailstone do
<syntaxhighlight lang="elixir">defmodule Hailstone do
require Integer
require Integer
Line 3,955: Line 3,955:
end
end


Hailstone.run</lang>
Hailstone.run</syntaxhighlight>


{{out}}
{{out}}
Line 3,964: Line 3,964:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>-module(hailstone).
<syntaxhighlight lang="erlang">-module(hailstone).
-import(io).
-import(io).
-export([main/0]).
-export([main/0]).
Line 3,987: Line 3,987:
io:format("finding maximum hailstone(N) length for 1 <= N <= 100000..."),
io:format("finding maximum hailstone(N) length for 1 <= N <= 100000..."),
{Length, N} = max_length(1, 100000),
{Length, N} = max_length(1, 100000),
io:format(" done.~nhailstone(~B) length: ~B~n", [N, Length]).</lang>
io:format(" done.~nhailstone(~B) length: ~B~n", [N, Length]).</syntaxhighlight>
{{out}}
{{out}}
<pre>Eshell V5.8.4 (abort with ^G)
<pre>Eshell V5.8.4 (abort with ^G)
Line 4,006: Line 4,006:
This version has one collatz function for just calculating totals (just for fun) and the second generating lists.
This version has one collatz function for just calculating totals (just for fun) and the second generating lists.


<lang erlang>
<syntaxhighlight lang="erlang">
-module(collatz).
-module(collatz).
-export([main/0,collatz/1,coll/1,max_atz_under/1]).
-export([main/0,collatz/1,coll/1,max_atz_under/1]).
Line 4,035: Line 4,035:
io:format("Max: ~w~n", [max_atz_under(100000)]),
io:format("Max: ~w~n", [max_atz_under(100000)]),
io:format("Total: ~w~n", [ length( Seq1000 ) ] ).
io:format("Total: ~w~n", [ length( Seq1000 ) ] ).
</syntaxhighlight>
</lang>
'''Output'''
'''Output'''
<pre>
<pre>
Line 4,051: Line 4,051:
=={{header|ERRE}}==
=={{header|ERRE}}==
In Italy it's known also as "Ulam conjecture".
In Italy it's known also as "Ulam conjecture".
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM ULAM
PROGRAM ULAM


Line 4,082: Line 4,082:
PRINT("Max. number is";NMAX;" with";MAX_COUNT;"elements")
PRINT("Max. number is";NMAX;" with";MAX_COUNT;"elements")
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 4,114: Line 4,114:
=={{header|Euler Math Toolbox}}==
=={{header|Euler Math Toolbox}}==


<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function hailstone (n) ...
>function hailstone (n) ...
$ v=[n];
$ v=[n];
Line 4,159: Line 4,159:
351
351
77031
77031
</syntaxhighlight>
</lang>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>function hailstone(atom n)
<syntaxhighlight lang="euphoria">function hailstone(atom n)
sequence s
sequence s
s = {n}
s = {n}
Line 4,207: Line 4,207:


printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",
printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",
{imax,max})</lang>
{imax,max})</syntaxhighlight>
{{out}}
{{out}}
<pre>hailstone(27) =
<pre>hailstone(27) =
Line 4,232: Line 4,232:
Ezhil is a Tamil programming language, see [http://en.wikipedia.org/wiki/Ezhil_%28programming_language%29 | Wikipedia] entry.
Ezhil is a Tamil programming language, see [http://en.wikipedia.org/wiki/Ezhil_%28programming_language%29 | Wikipedia] entry.


<lang src="Python">
<syntaxhighlight lang="src="python"">
நிரல்பாகம் hailstone ( எண் )
நிரல்பாகம் hailstone ( எண் )
பதிப்பி "=> ",எண் #hailstone seq
பதிப்பி "=> ",எண் #hailstone seq
Line 4,253: Line 4,253:
பதிப்பி "**********************************************"
பதிப்பி "**********************************************"
முடி
முடி
</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>let rec hailstone n = seq {
<syntaxhighlight lang="fsharp">let rec hailstone n = seq {
match n with
match n with
| 1 -> yield 1
| 1 -> yield 1
Line 4,269: Line 4,269:


let maxLen, maxI = Seq.max <| seq { for i in 1..99999 -> Seq.length (hailstone i), i}
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>
printfn "Maximum length %d was found for hailstone(%d)" maxLen maxI</syntaxhighlight>
{{out}}
{{out}}
<pre>Maximum length 351 was found for hailstone(77031)</pre>
<pre>Maximum length 351 was found for hailstone(77031)</pre>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>! rosetta/hailstone/hailstone.factor
<syntaxhighlight lang="factor">! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone
IN: rosetta.hailstone
Line 4,304: Line 4,304:
PRIVATE>
PRIVATE>


MAIN: main</lang>
MAIN: main</syntaxhighlight>
{{out}}
{{out}}
<pre>$ ./factor -run=rosetta.hailstone
<pre>$ ./factor -run=rosetta.hailstone
Line 4,315: Line 4,315:


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>[$1&$[%3*1+0~]?~[2/]?]n:
<syntaxhighlight lang="false">[$1&$[%3*1+0~]?~[2/]?]n:
[[$." "$1>][n;!]#%]s:
[[$." "$1>][n;!]#%]s:
[1\[$1>][\1+\n;!]#%]c:
[1\[$1>][\1+\n;!]#%]c:
Line 4,322: Line 4,322:
0m:0f:
0m:0f:
1[$100000\>][$c;!$m;>[m:$f:0]?%1+]#%
1[$100000\>][$c;!$m;>[m:$f:0]?%1+]#%
f;." has hailstone sequence length "m;.</lang>
f;." has hailstone sequence length "m;.</syntaxhighlight>


=={{header|Fermat}}==
=={{header|Fermat}}==
<lang fermat>Array g[2]
<syntaxhighlight lang="fermat">Array g[2]


Func Collatz(n, d) =
Func Collatz(n, d) =
Line 4,350: Line 4,350:
g[1]:=champ;
g[1]:=champ;
g[2]:=record;
g[2]:=record;
.</lang>
.</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: hail-next ( n -- n )
<syntaxhighlight lang="forth">: hail-next ( n -- n )
dup 1 and if 3 * 1+ else 2/ then ;
dup 1 and if 3 * 1+ else 2/ then ;
: .hail ( n -- )
: .hail ( n -- )
Line 4,371: Line 4,371:
swap . ." has hailstone sequence length " . ;
swap . ." has hailstone sequence length " . ;


100000 longest-hail</lang>
100000 longest-hail</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
{{works with|Fortran|95 and later}}
<lang fortran>program Hailstone
<syntaxhighlight lang="fortran">program Hailstone
implicit none
implicit none


Line 4,423: Line 4,423:
end subroutine
end subroutine


end program</lang>
end program</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,436: Line 4,436:
{{Works with|Frege|3.21.586-g026e8d7}}
{{Works with|Frege|3.21.586-g026e8d7}}


<lang frege>module Hailstone where
<syntaxhighlight lang="frege">module Hailstone where


import Data.List (maximumBy)
import Data.List (maximumBy)
Line 4,455: Line 4,455:
let t4 = show $ drop (length h27 - 4) h27
let t4 = show $ drop (length h27 - 4) h27
putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4)
putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4)
putStrLn $ show $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000]</lang>
putStrLn $ show $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000]</syntaxhighlight>


{{out}}
{{out}}
Line 4,467: Line 4,467:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang="frink">
hailstone[n] :=
hailstone[n] :=
{
{
Line 4,498: Line 4,498:


println["$longestN has length $longestLen"]
println["$longestN has length $longestLen"]
</syntaxhighlight>
</lang>


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>def
<syntaxhighlight lang="funl">def
hailstone( 1 ) = [1]
hailstone( 1 ) = [1]
hailstone( n ) = n # hailstone( if 2|n then n/2 else n*3 + 1 )
hailstone( n ) = n # hailstone( if 2|n then n/2 else n*3 + 1 )
Line 4,511: Line 4,511:
val (n, len) = maxBy( snd, [(i, hailstone( i ).length()) | i <- 1:100000] )
val (n, len) = maxBy( snd, [(i, hailstone( i ).length()) | i <- 1:100000] )


println( n, len )</lang>
println( n, len )</syntaxhighlight>


{{out}}
{{out}}
Line 4,521: Line 4,521:
=={{header|Futhark}}==
=={{header|Futhark}}==


<syntaxhighlight lang="futhark">
<lang Futhark>
fun hailstone_step(x: int): int =
fun hailstone_step(x: int): int =
if (x % 2) == 0
if (x % 2) == 0
Line 4,554: Line 4,554:
(hailstone_seq x,
(hailstone_seq x,
reduce max 0 (map hailstone_len (map (1+) (iota (n-1)))))
reduce max 0 (map hailstone_len (map (1+) (iota (n-1)))))
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>
<syntaxhighlight lang="futurebasic">
local fn Hailstone( n as NSInteger ) as NSInteger
local fn Hailstone( n as NSInteger ) as NSInteger
'~'1
'~'1
Line 4,618: Line 4,618:


HandleEvents
HandleEvents
</syntaxhighlight>
</lang>


{{output}}
{{output}}
Line 4,652: Line 4,652:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>CollatzSequence := function(n)
<syntaxhighlight lang="gap">CollatzSequence := function(n)
local v;
local v;
v := [ n ];
v := [ n ];
Line 4,711: Line 4,711:
# [ 77031, 351 ]
# [ 77031, 351 ]
CollatzMax(1, 1000000);
CollatzMax(1, 1000000);
# [ 837799, 525 ]</lang>
# [ 837799, 525 ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 4,748: Line 4,748:
}
}
fmt.Printf("hs(%d): %d elements\n", maxN, maxLen)
fmt.Printf("hs(%d): %d elements\n", maxN, maxLen)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,762: Line 4,762:


Output is the same as version above.
Output is the same as version above.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 4,829: Line 4,829:
}
}
fmt.Printf("hs(%d): %d elements\n", nMaxLen, computedLen[nMaxLen])
fmt.Printf("hs(%d): %d elements\n", nMaxLen, computedLen[nMaxLen])
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==
<lang groovy>def hailstone = { long start ->
<syntaxhighlight lang="groovy">def hailstone = { long start ->
def sequence = []
def sequence = []
while (start != 1) {
while (start != 1) {
Line 4,839: Line 4,839:
}
}
sequence << start
sequence << start
}</lang>
}</syntaxhighlight>
Test Code
Test Code
<lang groovy>def sequence = hailstone(27)
<syntaxhighlight lang="groovy">def sequence = hailstone(27)
assert sequence.size() == 112
assert sequence.size() == 112
assert sequence[0..3] == [27, 82, 41, 124]
assert sequence[0..3] == [27, 82, 41, 124]
Line 4,847: Line 4,847:


def results = (1..100000).collect { [n:it, size:hailstone(it).size()] }.max { it.size }
def results = (1..100000).collect { [n:it, size:hailstone(it).size()] }.max { it.size }
println results</lang>
println results</syntaxhighlight>
{{out}}
{{out}}
<pre>[n:77031, size:351]</pre>
<pre>[n:77031, size:351]</pre>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import Data.List (maximumBy)
<syntaxhighlight lang="haskell">import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.Ord (comparing)


Line 4,883: Line 4,883:
"The sequence has length: "
"The sequence has length: "
<> (show . length . hailstone $ longestChain)
<> (show . length . hailstone $ longestChain)
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Collatz sequence for 27:
<pre>Collatz sequence for 27:
Line 4,892: Line 4,892:


The following is an older version, which some of the language examples on this page are translated from:
The following is an older version, which some of the language examples on this page are translated from:
<lang haskell>import Data.Ord (comparing)
<syntaxhighlight lang="haskell">import Data.Ord (comparing)
import Data.List (maximumBy, intercalate)
import Data.List (maximumBy, intercalate)


Line 4,917: Line 4,917:
maximumBy (comparing fst) $
maximumBy (comparing fst) $
withResult (length . hailstone) <$> [1 .. 100000]
withResult (length . hailstone) <$> [1 .. 100000]
]</lang>
]</syntaxhighlight>
{{out}}
{{out}}
<pre>112
<pre>112
Line 4,928: Line 4,928:
One approach to using '''unfoldr''' and then '''foldr''' might be:
One approach to using '''unfoldr''' and then '''foldr''' might be:


<lang haskell>import Data.List (unfoldr)
<syntaxhighlight lang="haskell">import Data.List (unfoldr)




Line 4,978: Line 4,978:
, "length of this sequence:"
, "length of this sequence:"
, show maxLen
, show maxLen
]</lang>
]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Sequence 27 length:
<pre>Sequence 27 length:
Line 4,993: Line 4,993:


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>DIMENSION stones(1000)
<syntaxhighlight lang="hicest">DIMENSION stones(1000)


H27 = hailstone(27)
H27 = hailstone(27)
Line 5,026: Line 5,026:
ENDIF
ENDIF
ENDDO
ENDDO
END</lang>
END</syntaxhighlight>
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;
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;
<br /> number=77031; longest_sequence=351;
Line 5,032: Line 5,032:
=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
A simple solution that <i>generates</i> (in the Icon sense) the sequence is:
A simple solution that <i>generates</i> (in the Icon sense) the sequence is:
<lang icon>procedure hailstone(n)
<syntaxhighlight lang="icon">procedure hailstone(n)
while n > 1 do {
while n > 1 do {
suspend n
suspend n
Line 5,038: Line 5,038:
}
}
suspend 1
suspend 1
end</lang>
end</syntaxhighlight>
and a test program for this solution is:
and a test program for this solution is:
<lang icon>procedure main(args)
<syntaxhighlight lang="icon">procedure main(args)
n := integer(!args) | 27
n := integer(!args) | 27
every writes(" ",hailstone(n))
every writes(" ",hailstone(n))
end</lang>
end</syntaxhighlight>
but this solution is computationally expensive when run repeatedly (task 3).
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.
The following solution uses caching to improve performance on task 3 at the expense of space.
<lang icon>procedure hailstone(n)
<syntaxhighlight lang="icon">procedure hailstone(n)
static cache
static cache
initial {
initial {
Line 5,055: Line 5,055:
/cache[n] := [n] ||| hailstone(if n%2 = 0 then n/2 else 3*n+1)
/cache[n] := [n] ||| hailstone(if n%2 = 0 then n/2 else 3*n+1)
return cache[n]
return cache[n]
end</lang>
end</syntaxhighlight>


A test program is:
A test program is:
<lang icon>procedure main(args)
<syntaxhighlight lang="icon">procedure main(args)
n := integer(!args) | 27
n := integer(!args) | 27
task2(n)
task2(n)
Line 5,080: Line 5,080:
}
}
write(maxN," has a sequence of ",maxHS," values")
write(maxN," has a sequence of ",maxHS," values")
end</lang>
end</syntaxhighlight>
A sample run is:
A sample run is:
<pre>
<pre>
Line 5,101: Line 5,101:
This solution uses a cache to speed up the length calculation for larger numbers.
This solution uses a cache to speed up the length calculation for larger numbers.
{{works with|Glulx virtual machine}}
{{works with|Glulx virtual machine}}
<lang inform7>Home is a room.
<syntaxhighlight lang="inform7">Home is a room.


To decide which list of numbers is the hailstone sequence for (N - number):
To decide which list of numbers is the hailstone sequence for (N - number):
Line 5,153: Line 5,153:
let best number be N;
let best number be N;
say "The number under 100,000 with the longest hailstone sequence is [best number] with [best length] element[s].";
say "The number under 100,000 with the longest hailstone sequence is [best number] with [best length] element[s].";
end the story.</lang>
end the story.</syntaxhighlight>


{{out}}
{{out}}
Line 5,161: Line 5,161:
=={{header|Io}}==
=={{header|Io}}==
Here is a simple, brute-force approach:
Here is a simple, brute-force approach:
<syntaxhighlight lang="io">
<lang io>
makeItHail := method(n,
makeItHail := method(n,
stones := list(n)
stones := list(n)
Line 5,200: Line 5,200:
writeln("For numbers less than or equal to 100,000, ", nn,
writeln("For numbers less than or equal to 100,000, ", nn,
" has the longest sequence of ", numOfElems, " elements.")
" has the longest sequence of ", numOfElems, " elements.")
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,212: Line 5,212:
=={{header|Ioke}}==
=={{header|Ioke}}==
{{needs-review|Ioke|Calculates the Hailstone sequence but might not complete everything from task description.}}
{{needs-review|Ioke|Calculates the Hailstone sequence but might not complete everything from task description.}}
<lang ioke>collatz = method(n,
<syntaxhighlight lang="ioke">collatz = method(n,
n println
n println
unless(n <= 1,
unless(n <= 1,
if(n even?, collatz(n / 2), collatz(n * 3 + 1)))
if(n even?, collatz(n / 2), collatz(n * 3 + 1)))
)</lang>
)</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
'''Solution:'''
'''Solution:'''
<lang j>hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0</lang>
<syntaxhighlight lang="j">hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0</syntaxhighlight>
'''Usage:'''
'''Usage:'''
<lang j> # hailseq 27 NB. sequence length
<syntaxhighlight lang="j"> # hailseq 27 NB. sequence length
112
112
4 _4 {."0 1 hailseq 27 NB. first & last 4 numbers in sequence
4 _4 {."0 1 hailseq 27 NB. first & last 4 numbers in sequence
Line 5,228: Line 5,228:
8 4 2 1
8 4 2 1
(>:@(i. >./) , >./) #@hailseq }.i. 1e5 NB. number < 100000 with max seq length & its seq length
(>:@(i. >./) , >./) #@hailseq }.i. 1e5 NB. number < 100000 with max seq length & its seq length
77031 351</lang>
77031 351</syntaxhighlight>
See also the [[j:Essays/Collatz Conjecture|Collatz Conjecture essay on the J wiki]].
See also the [[j:Essays/Collatz Conjecture|Collatz Conjecture essay on the J wiki]].


=={{header|Java}}==
=={{header|Java}}==
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
<lang java5>import java.util.ArrayList;
<syntaxhighlight lang="java5">import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashMap;
import java.util.List;
import java.util.List;
Line 5,328: Line 5,328:
return;
return;
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{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]
<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 5,339: Line 5,339:
===ES5===
===ES5===
====Imperative====
====Imperative====
<lang javascript>function hailstone (n) {
<syntaxhighlight lang="javascript">function hailstone (n) {
var seq = [n];
var seq = [n];
while (n > 1) {
while (n > 1) {
Line 5,361: Line 5,361:
}
}
}
}
print("longest sequence: " + max + " numbers for starting point " + n);</lang>
print("longest sequence: " + max + " numbers for starting point " + n);</syntaxhighlight>
{{out}}
{{out}}
<pre>sequence 27 is (27, 82, 41, 124 ... 8, 4, 2, 1). length: 112
<pre>sequence 27 is (27, 82, 41, 124 ... 8, 4, 2, 1). length: 112
Line 5,374: Line 5,374:
(translating one of the Haskell solutions).
(translating one of the Haskell solutions).


<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {


// Hailstone Sequence
// Hailstone Sequence
Line 5,393: Line 5,393:
};
};


})();</lang>
})();</syntaxhighlight>


{{out}}
{{out}}


<lang JavaScript>{"length":112,"sequence":[27,82,41,124,62,31,94,47,142,71,214,
<syntaxhighlight lang="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,
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,
175,526, 263,790,395,1186,593,1780,890,445,1336,668,334,167,502,251,754,377,
Line 5,403: Line 5,403:
2429,7288,3644,1822,911,2734,1367,4102,2051,6154,3077,9232,4616,2308,1154,577,
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,
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]}</lang>
40,20,10,5,16,8,4,2,1]}</syntaxhighlight>


Attempting to fold that recursive function over an array of 100,000 elements,
Attempting to fold that recursive function over an array of 100,000 elements,
Line 5,412: Line 5,412:
which reuses previously calculated paths.
which reuses previously calculated paths.


<lang JavaScript>(function () {
<syntaxhighlight lang="javascript">(function () {


function memoizedHailstone() {
function memoizedHailstone() {
Line 5,461: Line 5,461:
return longestBelow(100000);
return longestBelow(100000);


})();</lang>
})();</syntaxhighlight>


{{out}}
{{out}}


<lang JavaScript>// Number, length of sequence
<syntaxhighlight lang="javascript">// Number, length of sequence
{"n":77031, "l":351}</lang>
{"n":77031, "l":351}</syntaxhighlight>


For better time (as well as space) we can continue to memoize while falling back to a function which returns the
For better time (as well as space) we can continue to memoize while falling back to a function which returns the
Line 5,473: Line 5,473:
for integers below one million, or ten million and beyond, without hitting the limits of system resources.
for integers below one million, or ten million and beyond, without hitting the limits of system resources.


<lang JavaScript>(function (n) {
<syntaxhighlight lang="javascript">(function (n) {


var dctMemo = {};
var dctMemo = {};
Line 5,525: Line 5,525:
return [100000, 1000000, 10000000].map(longestBelow);
return [100000, 1000000, 10000000].map(longestBelow);


})();</lang>
})();</syntaxhighlight>


{{out}}
{{out}}


<syntaxhighlight lang="javascript">[
<lang JavaScript>[
{"n":77031, "l":351}, // 100,000
{"n":77031, "l":351}, // 100,000
{"n":837799, "l":525}, // 1,000,000
{"n":837799, "l":525}, // 1,000,000
{"n":8400511, "l":686} // 10,000,000
{"n":8400511, "l":686} // 10,000,000
]</lang>
]</syntaxhighlight>


<lang JavaScript>longestBelow(100000000)
<syntaxhighlight lang="javascript">longestBelow(100000000)
-> {"n":63728127, "l":950}</lang>
-> {"n":63728127, "l":950}</syntaxhighlight>


===ES6===
===ES6===
<lang javascript>(() => {
<syntaxhighlight lang="javascript">(() => {


// hailstones :: Int -> [Int]
// hailstones :: Int -> [Int]
Line 5,642: Line 5,642:
`The length of that sequence is ${maxLen}.`
`The length of that sequence is ${maxLen}.`
]);
]);
})();</lang>
})();</syntaxhighlight>
{{Out}}
{{Out}}
(Run in the Atom editor, through the Script package)
(Run in the Atom editor, through the Script package)
Line 5,664: Line 5,664:
=={{header|jq}}==
=={{header|jq}}==
{{works with|jq|1.4}}
{{works with|jq|1.4}}
<lang jq># Generate the hailstone sequence as a stream to save space (and time) when counting
<syntaxhighlight lang="jq"># Generate the hailstone sequence as a stream to save space (and time) when counting
def hailstone:
def hailstone:
recurse( if . > 1 then
recurse( if . > 1 then
Line 5,679: Line 5,679:
([0,0];
([0,0];
($i | count(hailstone)) as $l
($i | count(hailstone)) as $l
| if $l > .[1] then [$i, $l] else . end);</lang>
| if $l > .[1] then [$i, $l] else . end);</syntaxhighlight>
'''Examples''':
'''Examples''':
<lang jq>[27|hailstone] as $h
<syntaxhighlight lang="jq">[27|hailstone] as $h
| "[27|hailstone]|length is \($h|length)",
| "[27|hailstone]|length is \($h|length)",
"The first four numbers: \($h[0:4])",
"The first four numbers: \($h[0:4])",
Line 5,687: Line 5,687:
"",
"",
max_hailstone(100000) as $m
max_hailstone(100000) as $m
| "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))"</lang>
| "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))"</syntaxhighlight>
{{out}}
{{out}}
<lang sh>$ jq -M -r -n -f hailstone.jq
<syntaxhighlight lang="sh">$ jq -M -r -n -f hailstone.jq
[27|hailstone]|length is 112
[27|hailstone]|length is 112
The first four numbers: [27,82,41,124]
The first four numbers: [27,82,41,124]
The last four numbers: [8,4,2,1]
The last four numbers: [8,4,2,1]


Maximum length for n|hailstone for n in 1..100000 is 351 (n == 77031)</lang>
Maximum length for n|hailstone for n in 1..100000 is 351 (n == 77031)</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Line 5,700: Line 5,700:


===Dynamic solution===
===Dynamic solution===
<lang julia>function hailstonelength(n::Integer)
<syntaxhighlight lang="julia">function hailstonelength(n::Integer)
len = 1
len = 1
while n > 1
while n > 1
Line 5,710: Line 5,710:


@show hailstonelength(27); nothing
@show hailstonelength(27); nothing
@show findmax([hailstonelength(i) for i in 1:100_000]); nothing</lang>
@show findmax([hailstonelength(i) for i in 1:100_000]); nothing</syntaxhighlight>


{{out}}
{{out}}
Line 5,721: Line 5,721:
====Julia 1.0====
====Julia 1.0====
{{works with|Julia|1.0+}}
{{works with|Julia|1.0+}}
<lang julia>struct HailstoneSeq{T<:Integer}
<syntaxhighlight lang="julia">struct HailstoneSeq{T<:Integer}
count::T
count::T
end
end
Line 5,759: Line 5,759:
Base.isless(h::HailstoneSeq, s::HailstoneSeq) = length(h) < length(s)
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)))</lang>
println("The number with the longest sequence under 100,000 is: ", maximum(HailstoneSeq.(1:100_000)))</syntaxhighlight>


{{out}}
{{out}}
Line 5,770: Line 5,770:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>struct HailstoneSeq{T<:Integer}
<syntaxhighlight lang="julia">struct HailstoneSeq{T<:Integer}
start::T
start::T
end
end
Line 5,809: Line 5,809:


Base.isless(h::HailstoneSeq, s::HailstoneSeq) = length(h) < length(s)
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)))</lang>
println("The number with the longest sequence under 100,000 is: ", maximum(HailstoneSeq.(1:100_000)))</syntaxhighlight>


{{out}}
{{out}}
Line 5,818: Line 5,818:


=={{header|K}}==
=={{header|K}}==
<lang k> hail: (1<){:[x!2;1+3*x;_ x%2]}\
<syntaxhighlight lang="k"> hail: (1<){:[x!2;1+3*x;_ x%2]}\
seqn: hail 27
seqn: hail 27


Line 5,829: Line 5,829:


{m,x@s?m:|/s:{#hail x}'x}{x@&x!2}!:1e5
{m,x@s?m:|/s:{#hail x}'x}{x@&x!2}!:1e5
351 77031</lang>
351 77031</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang kotlin>import java.util.ArrayDeque
<syntaxhighlight lang="kotlin">import java.util.ArrayDeque


fun hailstone(n: Int): ArrayDeque<Int> {
fun hailstone(n: Int): ArrayDeque<Int> {
Line 5,855: Line 5,855:
println("${longestHail.first} is the number less than 100000 with " +
println("${longestHail.first} is the number less than 100000 with " +
"the longest sequence, having length ${longestHail.size}.")
"the longest sequence, having length ${longestHail.size}.")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,862: Line 5,862:


=={{header|Lasso}}==
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">[
<lang Lasso>[
define_tag("hailstone", -required="n", -type="integer", -copy);
define_tag("hailstone", -required="n", -type="integer", -copy);
local("sequence") = array(#n);
local("sequence") = array(#n);
Line 5,893: Line 5,893:
"<br/>";
"<br/>";
"Number with the longest sequence under 100,000: " #longest_index + ", with " + #longest_sequence + " elements.";
"Number with the longest sequence under 100,000: " #longest_index + ", with " + #longest_sequence + " elements.";
]</lang>
]</syntaxhighlight>


=={{header|Limbo}}==
=={{header|Limbo}}==


<lang>implement Hailstone;
<syntaxhighlight lang="text">implement Hailstone;


include "sys.m"; sys: Sys;
include "sys.m"; sys: Sys;
Line 5,949: Line 5,949:
return i :: hailstone((big 3 * i) + big 1);
return i :: hailstone((big 3 * i) + big 1);
}
}
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 5,957: Line 5,957:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>on hailstone (n, sequenceList)
<syntaxhighlight lang="lingo">on hailstone (n, sequenceList)
len = 1
len = 1
repeat while n<>1
repeat while n<>1
Line 5,970: Line 5,970:
if listP(sequenceList) then sequenceList.add(n)
if listP(sequenceList) then sequenceList.add(n)
return len
return len
end</lang>
end</syntaxhighlight>
Usage:
Usage:
<lang lingo>sequenceList = []
<syntaxhighlight lang="lingo">sequenceList = []
hailstone(27, sequenceList)
hailstone(27, sequenceList)
put sequenceList
put sequenceList
Line 5,987: Line 5,987:
end repeat
end repeat
put n, maxLen
put n, maxLen
-- 77031 351</lang>
-- 77031 351</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to hail.next :n
<syntaxhighlight lang="logo">to hail.next :n
output ifelse equal? 0 modulo :n 2 [:n/2] [3*:n + 1]
output ifelse equal? 0 modulo :n 2 [:n/2] [3*:n + 1]
end
end
Line 6,012: Line 6,012:
end
end


max.hail 100000</lang>
max.hail 100000</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
<lang logtalk>:- object(hailstone).
<syntaxhighlight lang="logtalk">:- object(hailstone).


:- public(generate_sequence/2).
:- public(generate_sequence/2).
Line 6,108: Line 6,108:
).
).


:- end_object.</lang>
:- end_object.</syntaxhighlight>
Testing:
Testing:
<lang logtalk>| ?- hailstone::write_sequence(27).
<syntaxhighlight 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
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
true
Line 6,120: Line 6,120:
| ?- hailstone::longest_sequence(1, 100000, N, Length).
| ?- hailstone::longest_sequence(1, 100000, N, Length).
N = 77031, Length = 351
N = 77031, Length = 351
true</lang>
true</syntaxhighlight>


=={{header|LOLCODE}}==
=={{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.
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.
<lang LOLCODE>HAI 1.3
<syntaxhighlight lang="lolcode">HAI 1.3


HOW IZ I hailin YR stone
HOW IZ I hailin YR stone
Line 6,172: Line 6,172:
VISIBLE "len(hail(" max ")) = " len
VISIBLE "len(hail(" max ")) = " len


KTHXBYE</lang>
KTHXBYE</syntaxhighlight>
{{out}}
{{out}}
<pre>hail(27) = 27 82 41 124 ... 8 4 2 1, length = 112
<pre>hail(27) = 27 82 41 124 ... 8 4 2 1, length = 112
Line 6,178: Line 6,178:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function hailstone( n, print_numbers )
<syntaxhighlight lang="lua">function hailstone( n, print_numbers )
local n_iter = 1
local n_iter = 1


Line 6,207: Line 6,207:
end
end


print( string.format( "Needed %d iterations for the number %d.\n", max_iter, max_i ) )</lang>
print( string.format( "Needed %d iterations for the number %d.\n", max_iter, max_i ) )</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
Line 6,213: Line 6,213:


Also we use current stack as FIFO to get the last 4 numbers
Also we use current stack as FIFO to get the last 4 numbers
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module hailstone.Task {
Module hailstone.Task {
hailstone=lambda (n as long)->{
hailstone=lambda (n as long)->{
Line 6,262: Line 6,262:
}
}
hailstone.Task
hailstone.Task
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 6,273: Line 6,273:
=={{header|Maple}}==
=={{header|Maple}}==
Define the procedure:
Define the procedure:
<syntaxhighlight lang="maple">
<lang Maple>
hailstone := proc( N )
hailstone := proc( N )
local n := N, HS := Array([n]);
local n := N, HS := Array([n]);
Line 6,286: Line 6,286:
HS;
HS;
end proc;
end proc;
</syntaxhighlight>
</lang>
Run the command and show the appropriate portion of the result;
Run the command and show the appropriate portion of the result;
<syntaxhighlight lang="maple">
<lang Maple>
> r := hailstone(27):
> r := hailstone(27):
[ 1..112 1-D Array ]
[ 1..112 1-D Array ]
Line 6,296: Line 6,296:
> r(1..4) ... r(-4..);
> r(1..4) ... r(-4..);
[27, 82, 41, 124] .. [8, 4, 2, 1]
[27, 82, 41, 124] .. [8, 4, 2, 1]
</syntaxhighlight>
</lang>
Compute the first 100000 sequences:
Compute the first 100000 sequences:
<syntaxhighlight lang="maple">
<lang Maple>
longest := 0; n := 0;
longest := 0; n := 0;
for i from 1 to 100000 do
for i from 1 to 100000 do
Line 6,308: Line 6,308:
od:
od:
printf("The longest Hailstone sequence in the first 100k is n=%d, with %d terms\n",n,longest);
printf("The longest Hailstone sequence in the first 100k is n=%d, with %d terms\n",n,longest);
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 6,318: Line 6,318:


=== Nested function call formulation ===
=== Nested function call formulation ===
<lang Mathematica>HailstoneF[n_] := NestWhileList[If[OddQ[#], 3 # + 1, #/2] &, n, # > 1 &]</lang>
<syntaxhighlight lang="mathematica">HailstoneF[n_] := NestWhileList[If[OddQ[#], 3 # + 1, #/2] &, n, # > 1 &]</syntaxhighlight>


This is probably the most readable and shortest implementation.
This is probably the most readable and shortest implementation.


=== Fixed-Point formulation ===
=== Fixed-Point formulation ===
<lang Mathematica>HailstoneFP[n_] := Most@FixedPointList[Switch[#, 1, 1, _?OddQ , 3# + 1, _, #/2] &, n]</lang>
<syntaxhighlight lang="mathematica">HailstoneFP[n_] := Most@FixedPointList[Switch[#, 1, 1, _?OddQ , 3# + 1, _, #/2] &, n]</syntaxhighlight>


=== Recursive formulation ===
=== Recursive formulation ===
<lang Mathematica>HailstoneR[1] = {1}
<syntaxhighlight lang="mathematica">HailstoneR[1] = {1}
HailstoneR[n_?OddQ] := Prepend[HailstoneR[3 n + 1], n]
HailstoneR[n_?OddQ] := Prepend[HailstoneR[3 n + 1], n]
HailstoneR[n_] := Prepend[HailstoneR[n/2], n] </lang>
HailstoneR[n_] := Prepend[HailstoneR[n/2], n] </syntaxhighlight>


=== Procedural implementation ===
=== Procedural implementation ===
<lang Mathematica>HailstoneP[n_] := Module[{x = {n}, s = n},
<syntaxhighlight lang="mathematica">HailstoneP[n_] := Module[{x = {n}, s = n},
While[s > 1, x = {x, s = If[OddQ@s, 3 s + 1, s/2]}]; Flatten@x] </lang>
While[s > 1, x = {x, s = If[OddQ@s, 3 s + 1, s/2]}]; Flatten@x] </syntaxhighlight>


=== Validation ===
=== Validation ===


I use this version to do the validation:
I use this version to do the validation:
<lang Mathematica>Hailstone[n_] :=
<syntaxhighlight lang="mathematica">Hailstone[n_] :=
NestWhileList[If[Mod[#, 2] == 0, #/2, ( 3*# + 1) ] &, n, # != 1 &];
NestWhileList[If[Mod[#, 2] == 0, #/2, ( 3*# + 1) ] &, n, # != 1 &];


Line 6,350: Line 6,350:
{i, 100000}
{i, 100000}
]
]
Print["Longest Hailstone sequence at n = ", longest, "\nwith length = ", comp]; </lang>
Print["Longest Hailstone sequence at n = ", longest, "\nwith length = ", comp]; </syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,361: Line 6,361:


==== Sequence 27 ====
==== Sequence 27 ====
<lang Mathematica>With[{seq = HailstoneFP[27]}, { Length[seq], Take[seq, 4], Take[seq, -4]}]</lang>
<syntaxhighlight lang="mathematica">With[{seq = HailstoneFP[27]}, { Length[seq], Take[seq, 4], Take[seq, -4]}]</syntaxhighlight>
{{out}}
{{out}}
<pre>{112, {27, 82, 41, 124}, {8, 4, 2, 1}}</pre>
<pre>{112, {27, 82, 41, 124}, {8, 4, 2, 1}}</pre>


Alternatively,
Alternatively,
<lang Mathematica>Short[HailstoneFP[27],0.45]</lang>
<syntaxhighlight lang="mathematica">Short[HailstoneFP[27],0.45]</syntaxhighlight>


{{out}}
{{out}}
Line 6,372: Line 6,372:


==== Longest sequence length ====
==== Longest sequence length ====
<lang Mathematica>MaximalBy[Table[{i, Length[HailstoneFP[i]]}, {i, 100000}], Last]</lang>
<syntaxhighlight lang="mathematica">MaximalBy[Table[{i, Length[HailstoneFP[i]]}, {i, 100000}], Last]</syntaxhighlight>
{{out}}
{{out}}
<pre>{{77031, 351}}</pre>
<pre>{{77031, 351}}</pre>
Line 6,378: Line 6,378:
=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
===Hailstone Sequence For N===
===Hailstone Sequence For N===
<lang Matlab>function x = hailstone(n)
<syntaxhighlight lang="matlab">function x = hailstone(n)
x = n;
x = n;
while n > 1
while n > 1
Line 6,388: Line 6,388:
end
end
x(end + 1) = n; %#ok
x(end + 1) = n; %#ok
end</lang>
end</syntaxhighlight>
Show sequence of hailstone(27) and number of elements:
Show sequence of hailstone(27) and number of elements:
<lang Matlab>x = hailstone(27);
<syntaxhighlight lang="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))</lang>
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))</syntaxhighlight>
{{out}}
{{out}}
<pre>hailstone(27): 27 82 41 124 ... 8 4 2 1
<pre>hailstone(27): 27 82 41 124 ... 8 4 2 1
Line 6,398: Line 6,398:
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length:
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)====
====Basic Version (use the above routine)====
<lang Matlab>N = 1e5;
<syntaxhighlight lang="matlab">N = 1e5;
maxLen = 0;
maxLen = 0;
for k = 1:N
for k = 1:N
Line 6,406: Line 6,406:
n = k;
n = k;
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>n = 77031
<pre>n = 77031
maxLen = 351</pre>
maxLen = 351</pre>
====Faster Version====
====Faster Version====
<lang matlab>function [n, maxLen] = longestHailstone(N)
<syntaxhighlight lang="matlab">function [n, maxLen] = longestHailstone(N)
maxLen = 0;
maxLen = 0;
for k = 1:N
for k = 1:N
Line 6,428: Line 6,428:
n = k;
n = k;
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<lang matlab>>> [n, maxLen] = longestHailstone(1e5)
<syntaxhighlight lang="matlab">>> [n, maxLen] = longestHailstone(1e5)
n = 77031
n = 77031
maxLen = 351</lang>
maxLen = 351</syntaxhighlight>
====Much Faster Version With Caching====
====Much Faster Version With Caching====
<lang matlab>function [n, maxLen] = longestHailstone(N)
<syntaxhighlight lang="matlab">function [n, maxLen] = longestHailstone(N)
lenList(N) = 0;
lenList(N) = 0;
lenList(1) = 1;
lenList(1) = 1;
Line 6,455: Line 6,455:
n = k;
n = k;
end
end
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<lang matlab>>> [n, maxLen] = longestHailstone(1e5)
<syntaxhighlight lang="matlab">>> [n, maxLen] = longestHailstone(1e5)
n = 77031
n = 77031
maxLen = 351</lang>
maxLen = 351</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>collatz(n) := block([L], L: [n], while n > 1 do
<syntaxhighlight 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)$
(n: if evenp(n) then n/2 else 3*n + 1, L: endcons(n, L)), L)$


Line 6,476: Line 6,476:
length(%); /* 112 */
length(%); /* 112 */
collatz_length(27); /* 112 */
collatz_length(27); /* 112 */
collatz_max(100000); /* [77031, 351] */</lang>
collatz_max(100000); /* [77031, 351] */</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
The actual calculation (including module ceremony)
The actual calculation (including module ceremony)
providing both a function and a predicate implementation:
providing both a function and a predicate implementation:
<lang mercury>:- module hailstone.
<syntaxhighlight lang="mercury">:- module hailstone.


:- interface.
:- interface.
Line 6,499: Line 6,499:
; hailstone(3 * N + 1, S) ).
; hailstone(3 * N + 1, S) ).


:- end_module hailstone.</lang>
:- end_module hailstone.</syntaxhighlight>


The mainline test driver (making use of [http://en.wikipedia.org/wiki/Unification_(computer_science) unification] for more succinct tests):
The mainline test driver (making use of [http://en.wikipedia.org/wiki/Unification_(computer_science) unification] for more succinct tests):
<lang mercury>:- module test_hailstone.
<syntaxhighlight lang="mercury">:- module test_hailstone.


:- interface.
:- interface.
Line 6,537: Line 6,537:
; io.write_string("At least one test failed.\n", !IO) ).
; io.write_string("At least one test failed.\n", !IO) ).


:- end_module test_hailstone.</lang>
:- end_module test_hailstone.</syntaxhighlight>


{{out}} of running this program is:
{{out}} of running this program is:
Line 6,544: Line 6,544:
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> …
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> …


<lang mercury>:- pred longest(int::in, int::out, int::out) is det.</lang>
<syntaxhighlight lang="mercury">:- pred longest(int::in, int::out, int::out) is det.</syntaxhighlight>


… you see that the second and third parameters are '''output''' parameters.
… you see that the second and third parameters are '''output''' parameters.
Line 6,557: Line 6,557:
=={{header|ML}}==
=={{header|ML}}==
==={{header|MLite}}===
==={{header|MLite}}===
<lang ocaml>fun hail (x = 1) = [1]
<syntaxhighlight lang="ocaml">fun hail (x = 1) = [1]
| (x rem 2 = 0) = x :: hail (x div 2)
| (x rem 2 = 0) = x :: hail (x div 2)
| x = x :: hail (x * 3 + 1)
| x = x :: hail (x * 3 + 1)
Line 6,591: Line 6,591:
print ` ref (biggest, 0);
print ` ref (biggest, 0);
print " and is of length ";
print " and is of length ";
println ` ref (biggest, 1);</lang>
println ` ref (biggest, 1);</syntaxhighlight>
{{out}}
{{out}}
<pre>hailstone sequence for the number 27 has 112 elements starting with [27, 82, 41, 124] and ending with [8, 4, 2, 1].
<pre>hailstone sequence for the number 27 has 112 elements starting with [27, 82, 41, 124] and ending with [8, 4, 2, 1].
Line 6,597: Line 6,597:


=={{header|Modula-2}}==
=={{header|Modula-2}}==
<lang modula2>MODULE hailst;
<syntaxhighlight lang="modula2">MODULE hailst;


IMPORT InOut;
IMPORT InOut;
Line 6,669: Line 6,669:
FindMax (100000);
FindMax (100000);
InOut.WriteString ("Done."); InOut.WriteLn
InOut.WriteString ("Done."); InOut.WriteLn
END hailst.</lang>
END hailst.</syntaxhighlight>
Producing:
Producing:
<pre>jan@Beryllium:~/modula/rosetta$ hailst
<pre>jan@Beryllium:~/modula/rosetta$ hailst
Line 6,697: Line 6,697:


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<lang MUMPS>hailstone(n) ;
<syntaxhighlight lang="mumps">hailstone(n) ;
If n=1 Quit n
If n=1 Quit n
If n#2 Quit n_" "_$$hailstone(3*n+1)
If n#2 Quit n_" "_$$hailstone(3*n+1)
Quit n_" "_$$hailstone(n\2)
Quit n_" "_$$hailstone(n\2)
Set x=$$hailstone(27) Write !,$Length(x," ")," terms in ",x,!
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</lang>
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</syntaxhighlight>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang Nanoquery>def hailstone(n)
<syntaxhighlight lang="nanoquery">def hailstone(n)
seq = list()
seq = list()
Line 6,736: Line 6,736:
end
end
print "\nThe number less than 100,000 with the longest sequence is "
print "\nThe number less than 100,000 with the longest sequence is "
println maxLoc + " with a length of " + max</lang>
println maxLoc + " with a length of " + max</syntaxhighlight>
{{out}}
{{out}}
<pre>hailstone(27)
<pre>hailstone(27)
Line 6,745: Line 6,745:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols binary
options replace format comments java crossref savelog symbols binary
Line 6,788: Line 6,788:
hs = hs' 'hn
hs = hs' 'hn


return hs.strip</lang>
return hs.strip</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 6,798: Line 6,798:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>proc hailstone(n: int): seq[int] =
<syntaxhighlight lang="nim">proc hailstone(n: int): seq[int] =
result = @[n]
result = @[n]
var n = n
var n = n
Line 6,823: Line 6,823:
m = n
m = n
mi = i
mi = i
echo &"\nFor numbers < 100_000, maximum length {m} was found for Hailstone({mi})."</lang>
echo &"\nFor numbers < 100_000, maximum length {m} was found for Hailstone({mi})."</syntaxhighlight>
{{out}}
{{out}}
<pre>Hailstone sequence for number 27 has 112 elements.
<pre>Hailstone sequence for number 27 has 112 elements.
Line 6,831: Line 6,831:


=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
<lang oberon2>MODULE hailst;
<syntaxhighlight lang="oberon2">MODULE hailst;


IMPORT Out;
IMPORT Out;
Line 6,910: Line 6,910:
Out.String ("Done.");
Out.String ("Done.");
Out.Ln
Out.Ln
END hailst.</lang>
END hailst.</syntaxhighlight>
Producing
Producing
<pre>
<pre>
Line 6,938: Line 6,938:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>#load "nums.cma";;
<syntaxhighlight lang="ocaml">#load "nums.cma";;
open Num;;
open Num;;


Line 7,000: Line 7,000:
"1732"; "866"; "433"; "1300"; "650"; "325"; "976"; "488"; "244"; "122";
"1732"; "866"; "433"; "1300"; "650"; "325"; "976"; "488"; "244"; "122";
"61"; "184"; "92"; "46"; "23"; "70"; "35"; "106"; "53"; "160"; "80"; "40";
"61"; "184"; "92"; "46"; "23"; "70"; "35"; "106"; "53"; "160"; "80"; "40";
"20"; "10"; "5"; "16"; "8"; "4"; "2"; "1"] *)</lang>
"20"; "10"; "5"; "16"; "8"; "4"; "2"; "1"] *)</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: hailstone // n -- [n]
<syntaxhighlight lang="oforth">: hailstone // n -- [n]
| l |
| l |
ListBuffer new ->l
ListBuffer new ->l
Line 7,011: Line 7,011:


hailstone(27) dup size println dup left(4) println right(4) println
hailstone(27) dup size println dup left(4) println right(4) println
100000 seq map(#[ dup hailstone size swap Pair new ]) reduce(#maxKey) println</lang>
100000 seq map(#[ dup hailstone size swap Pair new ]) reduce(#maxKey) println</syntaxhighlight>


{{out}}
{{out}}
Line 7,022: Line 7,022:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
sequence = hailstone(27)
sequence = hailstone(27)
say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]"
say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]"
Line 7,050: Line 7,050:
end
end
return sequence
return sequence
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 7,059: Line 7,059:
=={{header|Order}}==
=={{header|Order}}==
To display the length, and first and last elements, of the hailstone sequence for 27, we could do this:
To display the length, and first and last elements, of the hailstone sequence for 27, we could do this:
<lang c>#include <order/interpreter.h>
<syntaxhighlight lang="c">#include <order/interpreter.h>


#define ORDER_PP_DEF_8hailstone ORDER_PP_FN( \
#define ORDER_PP_DEF_8hailstone ORDER_PP_FN( \
Line 7,075: Line 7,075:
8(starts with:) 8seq_take(4, 8H) 8comma 8space
8(starts with:) 8seq_take(4, 8H) 8comma 8space
8(ends with:) 8seq_drop(8minus(8S, 4), 8H))
8(ends with:) 8seq_drop(8minus(8S, 4), 8H))
) )</lang>
) )</syntaxhighlight>
{{out}}
{{out}}
<lang>h(27) - length:112, starts with:(27)(82)(41)(124), ends with:(8)(4)(2)(1)</lang>
<syntaxhighlight lang="text">h(27) - length:112, starts with:(27)(82)(41)(124), ends with:(8)(4)(2)(1)</syntaxhighlight>


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:
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:
<lang c>#define ORDER_PP_DEF_8h_longest ORDER_PP_FN( \
<syntaxhighlight lang="c">#define ORDER_PP_DEF_8h_longest ORDER_PP_FN( \
8fn(8M, 8P, \
8fn(8M, 8P, \
8if(8is_0(8M), \
8if(8is_0(8M), \
Line 7,092: Line 7,092:
8let((8P, 8h_longest(8nat(1,0,0,0,0,0), 8pair(0, 0))),
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))))
8pair(8to_lit(8tuple_at_0(8P)), 8to_lit(8tuple_at_1(8P))))
)</lang>
)</syntaxhighlight>


...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):
...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):
<lang c>ORDER_PP(
<syntaxhighlight lang="c">ORDER_PP(
8let((8P,
8let((8P,
8seq_head(
8seq_head(
Line 7,103: Line 7,103:
8pair(8N, 8seq_size(8hailstone(8N)))),
8pair(8N, 8seq_size(8hailstone(8N)))),
8seq_iota(1, 8nat(1,0,0,0,0,0)))))),
8seq_iota(1, 8nat(1,0,0,0,0,0)))))),
8pair(8to_lit(8tuple_at_0(8P)), 8to_lit(8tuple_at_1(8P)))) )</lang>
8pair(8to_lit(8tuple_at_0(8P)), 8to_lit(8tuple_at_1(8P)))) )</syntaxhighlight>


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.
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}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {HailstoneSeq N}
fun {HailstoneSeq N}
N > 0 = true %% assert
N > 0 = true %% assert
Line 7,131: Line 7,131:
MaxI#MaxLen = {List.foldL Pairs MaxBy2nd 0#0}
MaxI#MaxLen = {List.foldL Pairs MaxBy2nd 0#0}
{System.showInfo
{System.showInfo
"Maximum length "#MaxLen#" was found for hailstone("#MaxI#")"}</lang>
"Maximum length "#MaxLen#" was found for hailstone("#MaxI#")"}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 7,140: Line 7,140:


===Version #1.===
===Version #1.===
<lang parigp>show(n)={
<syntaxhighlight lang="parigp">show(n)={
my(t=1);
my(t=1);
while(n>1,
while(n>1,
Line 7,170: Line 7,170:


show(27)
show(27)
r=0;for(n=1,1e5,t=len(n);if(t>r,r=t;ra=n));print(ra"\t"r)</lang>
r=0;for(n=1,1e5,t=len(n);if(t>r,r=t;ra=n));print(ra"\t"r)</syntaxhighlight>
{{out}}
{{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
<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 7,188: Line 7,188:
[http://oeis.org/A070165 A070165]
[http://oeis.org/A070165 A070165]


<lang parigp>
<syntaxhighlight lang="parigp">
\\ Get vector with Collatz sequence for the specified starting number.
\\ 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).
\\ Limit vector to the lim length, or less, if 1 (one) term is reached (when lim=0).
Line 7,211: Line 7,211:
Collatzmax(1,100000);
Collatzmax(1,100000);
}
}
</syntaxhighlight>
</lang>


{{Output}}
{{Output}}
Line 7,227: Line 7,227:
See [[Hailstone_sequence#Delphi | Delphi]]
See [[Hailstone_sequence#Delphi | Delphi]]
or try this transformed Delphi version without generics.Use of a static array.
or try this transformed Delphi version without generics.Use of a static array.
<lang pascal>program ShowHailstoneSequence;
<syntaxhighlight lang="pascal">program ShowHailstoneSequence;
{$IFDEF FPC}
{$IFDEF FPC}
{$MODE delphi} //or objfpc
{$MODE delphi} //or objfpc
Line 7,335: Line 7,335:
limit := limit*10;
limit := limit*10;
until Limit > maxN;
until Limit > maxN;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>sequence of 27 has 112 elements
<pre>sequence of 27 has 112 elements
Line 7,356: Line 7,356:
=={{header|Perl}}==
=={{header|Perl}}==
=== Straightforward ===
=== Straightforward ===
<lang Perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl


use warnings;
use warnings;
Line 7,392: Line 7,392:


return @sequence;
return @sequence;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 7,403: Line 7,403:
=== Compact ===
=== Compact ===
A more compact version:
A more compact version:
<lang Perl>#!/usr/bin/perl
<syntaxhighlight lang="perl">#!/usr/bin/perl
use strict;
use strict;


Line 7,417: Line 7,417:
@h = ();
@h = ();
for (1 .. 99_999) { @h = ($_, $h[2]) if ($h[2] = hailstone($_)) > $h[1] }
for (1 .. 99_999) { @h = ($_, $h[2]) if ($h[2] = hailstone($_)) > $h[1] }
printf "%d: (%d)\n", @h;</lang>
printf "%d: (%d)\n", @h;</syntaxhighlight>




Line 7,428: Line 7,428:
=={{header|Phix}}==
=={{header|Phix}}==
Copy of [[Hailstone_sequence#Euphoria|Euphoria]]
Copy of [[Hailstone_sequence#Euphoria|Euphoria]]
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<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>
<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>
Line 7,469: Line 7,469:
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 7,477: Line 7,477:


=={{header|PHP}}==
=={{header|PHP}}==
<lang php>function hailstone($n,$seq=array()){
<syntaxhighlight lang="php">function hailstone($n,$seq=array()){
$sequence = $seq;
$sequence = $seq;
$sequence[] = $n;
$sequence[] = $n;
Line 7,502: Line 7,502:
foreach($maxResult as $key => $val){
foreach($maxResult as $key => $val){
echo 'Number < 100000 with longest Hailstone seq.: ' . $key . ' with length of ' . $val;
echo 'Number < 100000 with longest Hailstone seq.: ' . $key . ' with length of ' . $val;
}</lang>
}</syntaxhighlight>
<pre>
<pre>
112 Elements.
112 Elements.
Line 7,510: Line 7,510:


=={{header|Picat}}==
=={{header|Picat}}==
<lang Picat>import util.
<syntaxhighlight lang="picat">import util.


go =>
go =>
Line 7,565: Line 7,565:
end,
end,
println([maxLen=MaxLen, maxN=MaxN]),
println([maxLen=MaxLen, maxN=MaxN]),
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 7,577: Line 7,577:
===Mode-directed tabling===
===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.)
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.)
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
time(max_chain(MaxN,MaxLen)),
time(max_chain(MaxN,MaxLen)),
printf("MaxN=%w,MaxLen=%w%n",MaxN,MaxLen).
printf("MaxN=%w,MaxLen=%w%n",MaxN,MaxLen).
Line 7,594: Line 7,594:
gen(3*N+1,Len1),
gen(3*N+1,Len1),
Len=Len1+1.
Len=Len1+1.
</syntaxhighlight>
</lang>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de hailstone (N)
<syntaxhighlight lang="picolisp">(de hailstone (N)
(make
(make
(until (= 1 (link N))
(until (= 1 (link N))
Line 7,609: Line 7,609:


(let N (maxi '((N) (length (hailstone N))) (range 1 100000))
(let N (maxi '((N) (length (hailstone N))) (range 1 100000))
(println N (length (hailstone N))) )</lang>
(println N (length (hailstone N))) )</syntaxhighlight>
{{out}}
{{out}}
<pre>27 112 (27 82 41 124) - (8 4 2 1)
<pre>27 112 (27 82 41 124) - (8 4 2 1)
Line 7,615: Line 7,615:


=={{header|Pike}}==
=={{header|Pike}}==
<lang Pike>#!/usr/bin/env pike
<syntaxhighlight lang="pike">#!/usr/bin/env pike


int next(int n)
int next(int n)
Line 7,653: Line 7,653:
}
}
write("longest sequence starting at %d has %d elements\n", longest->start, longest->length);
write("longest sequence starting at %d has %d elements\n", longest->start, longest->length);
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 7,662: Line 7,662:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli>test: proc options (main);
<syntaxhighlight lang="pli">test: proc options (main);
declare (longest, n) fixed (15);
declare (longest, n) fixed (15);
declare flag bit (1);
declare flag bit (1);
Line 7,699: Line 7,699:
end hailstones;
end hailstones;


end test;</lang>
end test;</syntaxhighlight>
{{out}}
{{out}}
<pre style="height:30ex;overflow:scroll">
<pre style="height:30ex;overflow:scroll">
Line 7,820: Line 7,820:


==={{header|PL/I-80}}===
==={{header|PL/I-80}}===
<lang PL/I>hailstone_demo: proc options (main);
<syntaxhighlight lang="pl/i">hailstone_demo: proc options (main);
%replace
%replace
true by '1'b,
true by '1'b,
Line 7,885: Line 7,885:


end hailstone_demo;
end hailstone_demo;
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Display hailstone sequence for what number? 27
<pre>Display hailstone sequence for what number? 27
Line 7,911: Line 7,911:
=={{header|plainTeX}}==
=={{header|plainTeX}}==
The following code works with any TeX engine.
The following code works with any TeX engine.
<lang tex>\newif\ifprint
<syntaxhighlight lang="tex">\newif\ifprint
\newcount\itercount
\newcount\itercount
\newcount\currentnum
\newcount\currentnum
Line 7,947: Line 7,947:
\repeat
\repeat
Seed max = \seed, length = \lenmax
Seed max = \seed, length = \lenmax
\bye</lang>
\bye</syntaxhighlight>


pdf or dvi output:
pdf or dvi output:
Line 7,961: Line 7,961:


=={{header|Pointless}}==
=={{header|Pointless}}==
<lang pointless>output =
<syntaxhighlight lang="pointless">output =
println(format(fmt,
println(format(fmt,
[seqLength, initSeq, tailSeq] ++ toList(longestPair)
[seqLength, initSeq, tailSeq] ++ toList(longestPair)
Line 7,996: Line 7,996:
step(n) =
step(n) =
if n % 2 == 0 then round(n / 2) else n * 3 + 1</lang>
if n % 2 == 0 then round(n / 2) else n * 3 + 1</syntaxhighlight>


{{out}}
{{out}}
Line 8,006: Line 8,006:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
{{works with|PowerShell|3.0+}}
{{works with|PowerShell|3.0+}}
<syntaxhighlight lang="powershell">
<lang Powershell>


function Get-HailStone {
function Get-HailStone {
Line 8,027: Line 8,027:
}
}
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 8,050: Line 8,050:
=={{header|Prolog}}==
=={{header|Prolog}}==
1. Create a routine to generate the hailstone sequence for a number.
1. Create a routine to generate the hailstone sequence for a number.
<lang prolog>hailstone(1,[1]) :- !.
<syntaxhighlight 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]) :- 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).</lang>
hailstone(N,[N|S]) :- 1 is N mod 2, N1 is (3 * N) + 1, hailstone(N1, S).</syntaxhighlight>


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.
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.
The following query performs the test.
<lang prolog>hailstone(27,X),
<syntaxhighlight lang="prolog">hailstone(27,X),
length(X,112),
length(X,112),
append([27, 82, 41, 124], _, X),
append([27, 82, 41, 124], _, X),
append(_, [8, 4, 2, 1], X).</lang>
append(_, [8, 4, 2, 1], X).</syntaxhighlight>


3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequences length.
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequences length.
<lang prolog>longestHailstoneSequence(M, Seq, Len) :- longesthailstone(M, 1, 1, Seq, Len).
<syntaxhighlight lang="prolog">longestHailstoneSequence(M, Seq, Len) :- longesthailstone(M, 1, 1, Seq, Len).
longesthailstone(1, Cn, Cl, Mn, Ml):- Mn = Cn,
longesthailstone(1, Cn, Cl, Mn, Ml):- Mn = Cn,
Ml = Cl.
Ml = Cl.
Line 8,072: Line 8,072:
longesthailstone(N1, N, L, Mn, Ml).
longesthailstone(N1, N, L, Mn, Ml).
longesthailstone(N, Cn, Cl, Mn, Ml) :- N1 is N-1,
longesthailstone(N, Cn, Cl, Mn, Ml) :- N1 is N-1,
longesthailstone(N1, Cn, Cl, Mn, Ml).</lang>
longesthailstone(N1, Cn, Cl, Mn, Ml).</syntaxhighlight>
run this query.
run this query.
<lang prolog>longestHailstoneSequence(100000, Seq, Len).</lang>
<syntaxhighlight lang="prolog">longestHailstoneSequence(100000, Seq, Len).</syntaxhighlight>
to get the following result
to get the following result
<pre>
<pre>
Line 8,085: Line 8,085:
Works with SWI-Prolog and module '''chr''' written by '''Tom Schrijvers''' and '''Jan Wielemaker''' <br>
Works with SWI-Prolog and module '''chr''' written by '''Tom Schrijvers''' and '''Jan Wielemaker''' <br>


<lang Prolog>:- use_module(library(chr)).
<syntaxhighlight lang="prolog">:- use_module(library(chr)).
:- chr_option(debug, off).
:- chr_option(debug, off).
:- chr_option(optimize, full).
:- chr_option(optimize, full).
Line 8,101: Line 8,101:
% Hailstone loop
% Hailstone loop
hailstone(1) ==> true.
hailstone(1) ==> true.
hailstone(N) ==> N \= 1 | collatz(N, H), hailstone(H).</lang>
hailstone(N) ==> N \= 1 | collatz(N, H), hailstone(H).</syntaxhighlight>


Code for task one :
Code for task one :
<lang Prolog>task1 :-
<syntaxhighlight lang="prolog">task1 :-
hailstone(27),
hailstone(27),
findall(X, find_chr_constraint(hailstone(X)), L),
findall(X, find_chr_constraint(hailstone(X)), L),
clean,
clean,
% check the requirements
% check the requirements
( (length(L, 112), append([27, 82, 41, 124 | _], [8,4,2,1], L)) -> writeln(ok); writeln(ko)).</lang>
( (length(L, 112), append([27, 82, 41, 124 | _], [8,4,2,1], L)) -> writeln(ok); writeln(ko)).</syntaxhighlight>
{{out}}
{{out}}
<pre> ?- task1.
<pre> ?- task1.
Line 8,115: Line 8,115:
true.</pre>
true.</pre>
Code for task two :
Code for task two :
<lang Prolog>longest_sequence :-
<syntaxhighlight lang="prolog">longest_sequence :-
seq(2, 100000, 1-[1], Len-V),
seq(2, 100000, 1-[1], Len-V),
format('For ~w sequence has ~w len ! ~n', [V, Len]).
format('For ~w sequence has ~w len ! ~n', [V, Len]).
Line 8,136: Line 8,136:
findall(hailstone(X), find_chr_constraint(hailstone(X)), L),
findall(hailstone(X), find_chr_constraint(hailstone(X)), L),
length(L, Len),
length(L, Len),
clean.</lang>
clean.</syntaxhighlight>
{{out}}
{{out}}
<pre> ?- longest_sequence.
<pre> ?- longest_sequence.
Line 8,144: Line 8,144:


=={{header|Pure}}==
=={{header|Pure}}==
<lang pure>// 1. Create a routine to generate the hailstone sequence for a number.
<syntaxhighlight lang="pure">// 1. Create a routine to generate the hailstone sequence for a number.
type odd x::int = x mod 2;
type odd x::int = x mod 2;
type even x::int = ~odd x;
type even x::int = ~odd x;
Line 8,172: Line 8,172:
(foldr (\ (a,b) (c,d) -> if (b > d) then (a,b) else (c,d))
(foldr (\ (a,b) (c,d) -> if (b > d) then (a,b) else (c,d))
(0,0)
(0,0)
(map (\ x -> (x, # hailstone x)) (1..100000)));</lang>
(map (\ x -> (x, # hailstone x)) (1..100000)));</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 8,181: Line 8,181:
=={{header|Python}}==
=={{header|Python}}==
===Procedural===
===Procedural===
<lang python>def hailstone(n):
<syntaxhighlight lang="python">def hailstone(n):
seq = [n]
seq = [n]
while n>1:
while n>1:
Line 8,192: Line 8,192:
assert len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]
assert len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]
print("Maximum length %i was found for hailstone(%i) for numbers <100,000" %
print("Maximum length %i was found for hailstone(%i) for numbers <100,000" %
max((len(hailstone(i)), i) for i in range(1,100000)))</lang>
max((len(hailstone(i)), i) for i in range(1,100000)))</syntaxhighlight>


{{out}}
{{out}}
Line 8,199: Line 8,199:
===Composition of pure functions===
===Composition of pure functions===
{{Works with|Python|3.7}}
{{Works with|Python|3.7}}
<lang python>'''Hailstone sequences'''
<syntaxhighlight lang="python">'''Hailstone sequences'''


from itertools import (islice, takewhile)
from itertools import (islice, takewhile)
Line 8,316: Line 8,316:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>The hailstone sequence for 27 has 112 elements,
<pre>The hailstone sequence for 27 has 112 elements,
Line 8,326: Line 8,326:


=={{header|Quackery}}==
=={{header|Quackery}}==
<lang Quackery>[ 1 & ] is odd ( n --> b )
<syntaxhighlight lang="quackery">[ 1 & ] is odd ( n --> b )
[ []
[ []
Line 8,360: Line 8,360:
longest take echo
longest take echo
say " has the longest sequence of any number less than 100000."
say " has the longest sequence of any number less than 100000."
cr say "It is " length take echo say " elements long." cr</lang>
cr say "It is " length take echo say " elements long." cr</syntaxhighlight>


'''Output:'''
'''Output:'''
<lang Quackery>The hailstone sequence for 27 has 112 elements.
<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.
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.
77031 has the longest sequence of any number less than 100000.
It is 351 elements long.
It is 351 elements long.
</syntaxhighlight>
</lang>


=={{header|R}}==
=={{header|R}}==
===Iterative solution===
===Iterative solution===
<lang rsplus>### PART 1:
<syntaxhighlight lang="rsplus">### PART 1:
makeHailstone <- function(n){
makeHailstone <- function(n){
hseq <- n
hseq <- n
Line 8,405: Line 8,405:
cat("Between ", lower.bound, " and ", upper.bound, ", the input of ",
cat("Between ", lower.bound, " and ", upper.bound, ", the input of ",
max.index, " gives the longest hailstone sequence, which has length ",
max.index, " gives the longest hailstone sequence, which has length ",
max.length, ". \n", sep="")</lang>
max.length, ". \n", sep="")</syntaxhighlight>


{{out}}
{{out}}
Line 8,425: Line 8,425:
===Vectorization solution===
===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:
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:
<lang rsplus>###Task 1:
<syntaxhighlight lang="rsplus">###Task 1:
collatz <- function(n)
collatz <- function(n)
{
{
Line 8,454: Line 8,454:
cat("The longest sequence before the 100000th is found at n =", longest, "and it has length", seqLenghts[longest], "\n")
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).
#Equivalently, line 1 could have been: seqLenghts <- sapply(Vectorize(collatz)(1:99999), length).
#Another good option would be seqLenghts <- lengths(Vectorize(collatz)(1:99999)).</lang>
#Another good option would be seqLenghts <- lengths(Vectorize(collatz)(1:99999)).</syntaxhighlight>
{{out}}
{{out}}
<pre>The first four elements are: 27 82 41 124 and the last four are: 8 4 2 1
<pre>The first four elements are: 27 82 41 124 and the last four are: 8 4 2 1
Line 8,460: Line 8,460:


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 8,481: Line 8,481:
(printf "for x<=~s, ~s has the longest sequence with ~s items\n"
(printf "for x<=~s, ~s has the longest sequence with ~s items\n"
N (car longest) (cdr longest))
N (car longest) (cdr longest))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 8,492: Line 8,492:
(formerly Perl 6)
(formerly Perl 6)


<lang perl6>sub hailstone($n) { $n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1 }
<syntaxhighlight lang="raku" line>sub hailstone($n) { $n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1 }


my @h = hailstone(27);
my @h = hailstone(27);
Line 8,499: Line 8,499:


my $m = max ( (1..99_999).race.map: { +hailstone($_) => $_ } );
my $m = max ( (1..99_999).race.map: { +hailstone($_) => $_ } );
say "Max length {$m.key} was found for hailstone({$m.value}) for numbers < 100_000";</lang>
say "Max length {$m.key} was found for hailstone({$m.value}) for numbers < 100_000";</syntaxhighlight>


{{out}}
{{out}}
Line 8,509: Line 8,509:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>
<syntaxhighlight lang="rebol">
hail: func [
hail: func [
"Returns the hailstone sequence for n"
"Returns the hailstone sequence for n"
Line 8,540: Line 8,540:
"the number less than 100000 with the longest hail sequence is"
"the number less than 100000 with the longest hail sequence is"
maxN "with length" maxLen
maxN "with length" maxLen
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 8,548: Line 8,548:
=={{header|REXX}}==
=={{header|REXX}}==
===non-optimized===
===non-optimized===
<lang rexx>/*REXX program tests a number and also a range for hailstone (Collatz) sequences. */
<syntaxhighlight lang="rexx">/*REXX program tests a number and also a range for hailstone (Collatz) sequences. */
numeric digits 20 /*be able to handle gihugeic numbers. */
numeric digits 20 /*be able to handle gihugeic numbers. */
parse arg x y . /*get optional arguments from the C.L. */
parse arg x y . /*get optional arguments from the C.L. */
Line 8,572: Line 8,572:
s= s n /* [↑] % is REXX integer division. */
s= s n /* [↑] % is REXX integer division. */
end /*#hs*/ /* [↑] append N to the sequence list*/
end /*#hs*/ /* [↑] append N to the sequence list*/
return s /*return the S string to the invoker.*/</lang>
return s /*return the S string to the invoker.*/</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 8,588: Line 8,588:
::::* &nbsp; previously calculated Collatz sequences (memoization)
::::* &nbsp; previously calculated Collatz sequences (memoization)
::::* &nbsp; a faster method of determining if an integer is even
::::* &nbsp; a faster method of determining if an integer is even
<lang rexx>/*REXX program tests a number and also a range for hailstone (Collatz) sequences. */
<syntaxhighlight lang="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". */
!.=0; !.0=1; !.2=1; !.4=1; !.6=1; !.8=1 /*assign even numerals to be "true". */
numeric digits 20; @.= 0 /*handle big numbers; initialize array.*/
numeric digits 20; @.= 0 /*handle big numbers; initialize array.*/
Line 8,623: Line 8,623:
if _>hm then iterate /*Is number out of range? Ignore it.*/
if _>hm then iterate /*Is number out of range? Ignore it.*/
@._= r /*assign subsequence number to array. */
@._= r /*assign subsequence number to array. */
end /*while*/; return s</lang>
end /*while*/; return s</syntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
<pre>
Line 8,642: Line 8,642:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
size = 27
size = 27
aList = []
aList = []
Line 8,663: Line 8,663:
see "" + aList[i] + " "
see "" + aList[i] + " "
next
next
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
This program uses new methods (Integer#even? and Enumerable#max_by) from Ruby 1.8.7.
This program uses new methods (Integer#even? and Enumerable#max_by) from Ruby 1.8.7.
{{works with|Ruby|1.8.7}}
{{works with|Ruby|1.8.7}}
<lang ruby>def hailstone n
<syntaxhighlight lang="ruby">def hailstone n
seq = [n]
seq = [n]
until n == 1
until n == 1
Line 8,684: Line 8,684:
n = (1 ... 100_000).max_by{|n| hailstone(n).length}
n = (1 ... 100_000).max_by{|n| hailstone(n).length}
puts "#{n} has a hailstone sequence length of #{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}"</lang>
puts "the largest number in that sequence is #{hailstone(n).max}"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 8,698: Line 8,698:
This avoids recomputing the end of the sequence.
This avoids recomputing the end of the sequence.
{{works with|Ruby|1.8.7}}
{{works with|Ruby|1.8.7}}
<lang ruby>module Hailstone
<syntaxhighlight lang="ruby">module Hailstone
ListNode = Struct.new(:value, :size, :succ) do
ListNode = Struct.new(:value, :size, :succ) do
def each
def each
Line 8,735: Line 8,735:
n = (1 ... 100_000).max_by{|n| Hailstone.sequence(n).size}
n = (1 ... 100_000).max_by{|n| Hailstone.sequence(n).size}
puts "#{n} has a hailstone sequence length of #{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}"</lang>
puts "the largest number in that sequence is #{Hailstone.sequence(n).max}"</syntaxhighlight>
output is the same as the above.
output is the same as the above.


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>fn hailstone(start : u32) -> Vec<u32> {
<syntaxhighlight lang="rust">fn hailstone(start : u32) -> Vec<u32> {
let mut res = Vec::new();
let mut res = Vec::new();
let mut next = start;
let mut next = start;
Line 8,778: Line 8,778:
}
}
println!("Longest sequence is {} element long for seed {}", max_len, max_seed);
println!("Longest sequence is {} element long for seed {}", max_len, max_seed);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>For 27 number of elements is 112
<pre>For 27 number of elements is 112
Line 8,785: Line 8,785:


=={{header|S-lang}}==
=={{header|S-lang}}==
<lang S-lang>% lst=1, return list of elements; lst=0 just return length
<syntaxhighlight lang="s-lang">% lst=1, return list of elements; lst=0 just return length
define hailstone(n, lst)
define hailstone(n, lst)
{
{
Line 8,829: Line 8,829:
}
}
}
}
() = printf("\n");</lang>
() = printf("\n");</syntaxhighlight>
{{out}}
{{out}}
<pre>Hailstone(27) has 112 elements starting with:
<pre>Hailstone(27) has 112 elements starting with:
Line 8,838: Line 8,838:


=={{header|SAS}}==
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
* Create a routine to generate the hailstone sequence for one number;
* Create a routine to generate the hailstone sequence for one number;
%macro gen_seq(n);
%macro gen_seq(n);
Line 8,893: Line 8,893:
%mend;
%mend;
%longest_hailstone(1,99999);
%longest_hailstone(1,99999);
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 8,910: Line 8,910:


=={{header|S-BASIC}}==
=={{header|S-BASIC}}==
<lang s-basic>comment
<syntaxhighlight lang="s-basic">comment
Compute and display "hailstone" (i.e., Collatz) sequence
Compute and display "hailstone" (i.e., Collatz) sequence
for a given number and find the longest sequence in the
for a given number and find the longest sequence in the
Line 8,972: Line 8,972:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Display hailstone sequence for what number? 27
<pre>Display hailstone sequence for what number? 27
Line 8,996: Line 8,996:
{{libheader|Scala}}
{{libheader|Scala}}
{{works with|Scala|2.10.2}}
{{works with|Scala|2.10.2}}
<lang Scala>object HailstoneSequence extends App {
<syntaxhighlight lang="scala">object HailstoneSequence extends App {
def hailstone(n: Int): Stream[Int] =
def hailstone(n: Int): Stream[Int] =
n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))
n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))
Line 9,010: Line 9,010:
val (n, len) = (1 until 100000).map(n => (n, hailstone(n).length)).maxBy(_._2)
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.")
println(s"Longest hailstone sequence length= $len occurring with number $n.")
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>Use the routine to show that the hailstone sequence for the number: 27.
<pre>Use the routine to show that the hailstone sequence for the number: 27.
Line 9,020: Line 9,020:


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (collatz n)
<syntaxhighlight lang="scheme">(define (collatz n)
(if (= n 1) '(1)
(if (= n 1) '(1)
(cons n (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n)))))))
(cons n (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n)))))))
Line 9,047: Line 9,047:


(collatz-max 1 100000)
(collatz-max 1 100000)
; (77031 351)</lang>
; (77031 351)</syntaxhighlight>


=={{header|Scilab}}==
=={{header|Scilab}}==
{{trans|MATLAB}}
{{trans|MATLAB}}
<lang>function x=hailstone(n)
<syntaxhighlight lang="text">function x=hailstone(n)
// iterative definition
// iterative definition
// usage: global verbose; verbose=%T; hailstone(27)
// usage: global verbose; verbose=%T; hailstone(27)
Line 9,083: Line 9,083:
M(k)=hailstone(k);
M(k)=hailstone(k);
end;
end;
[maxLength,n]=max(M)</lang>
[maxLength,n]=max(M)</syntaxhighlight>
{{out}}
{{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
<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 9,091: Line 9,091:


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func array integer: hailstone (in var integer: n) is func
const func array integer: hailstone (in var integer: n) is func
Line 9,148: Line 9,148:
writeln(" length=" <& length(h27));
writeln(" length=" <& length(h27));
writeln("Maximum length " <& maxLength <& " at number=" <& numberOfMaxLength);
writeln("Maximum length " <& maxLength <& " at number=" <& numberOfMaxLength);
end func;</lang>
end func;</syntaxhighlight>


{{out}}
{{out}}
Line 9,158: Line 9,158:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func hailstone (n) {
<syntaxhighlight lang="ruby">func hailstone (n) {
var sequence = [n]
var sequence = [n]
while (n > 1) {
while (n > 1) {
Line 9,181: Line 9,181:
}
}
 
 
printf("%d: (%d)\n", h...)</lang>
printf("%d: (%d)\n", h...)</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
{{works with|GNU Smalltalk}}
<lang smalltalk>Object subclass: Sequences [
<syntaxhighlight lang="smalltalk">Object subclass: Sequences [
Sequences class >> hailstone: n [
Sequences class >> hailstone: n [
|seq|
|seq|
Line 9,207: Line 9,207:
ifFalse: [ ^ Sequences hailstoneCount: ( (3*n) + 1) num: (m + 1) ].
ifFalse: [ ^ Sequences hailstoneCount: ( (3*n) + 1) num: (m + 1) ].
]
]
].</lang>
].</syntaxhighlight>


<lang smalltalk>|r|
<syntaxhighlight lang="smalltalk">|r|
r := Sequences hailstone: 27. "hailstone 'from' 27"
r := Sequences hailstone: 27. "hailstone 'from' 27"
(r size) displayNl. "its length"
(r size) displayNl. "its length"
Line 9,228: Line 9,228:


('Sequence generator %1, sequence length %2' % { (longest at: 1) . (longest at: 2) })
('Sequence generator %1, sequence length %2' % { (longest at: 1) . (longest at: 2) })
displayNl.</lang>
displayNl.</syntaxhighlight>


=={{header|SNUSP}}==
=={{header|SNUSP}}==
Line 9,243: Line 9,243:


=={{header|Swift}}==
=={{header|Swift}}==
<syntaxhighlight lang="swift">
<lang Swift>
func hailstone(var n:Int) -> [Int] {
func hailstone(var n:Int) -> [Int] {


Line 9,277: Line 9,277:
}
}


println("Longest sequence for numbers under 100,000 is with \(longest.n). Which has \(longest.len) items.")</lang>
println("Longest sequence for numbers under 100,000 is with \(longest.n). Which has \(longest.len) items.")</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 9,286: Line 9,286:
=={{header|Tcl}}==
=={{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.
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.
<lang tcl>proc hailstone n {
<syntaxhighlight lang="tcl">proc hailstone n {
while 1 {
while 1 {
lappend seq $n
lappend seq $n
Line 9,304: Line 9,304:
if {$l>$maxlen} {set maxlen $l;set max $i}
if {$l>$maxlen} {set maxlen $l;set max $i}
}
}
puts "max is $max, with length $maxlen"</lang>
puts "max is $max, with length $maxlen"</syntaxhighlight>


{{out}}
{{out}}
Line 9,316: Line 9,316:
=={{header|TI-83 BASIC}}==
=={{header|TI-83 BASIC}}==
===Task 1===
===Task 1===
<lang ti83b>prompt N
<syntaxhighlight lang="ti83b">prompt N
N→M: 0→X: 1→L
N→M: 0→X: 1→L
While L=1
While L=1
Line 9,330: Line 9,330:
End
End
End
End
{N,X}</lang>
{N,X}</syntaxhighlight>
{{out}}
{{out}}
<pre> 10
<pre> 10
Line 9,342: Line 9,342:
===Task 2===
===Task 2===
As the calculator is quite slow, so the output is for N=200
As the calculator is quite slow, so the output is for N=200
<lang ti83b>prompt N
<syntaxhighlight lang="ti83b">prompt N
0→A:0→B
0→A:0→B
for(I,1,N)
for(I,1,N)
Line 9,362: Line 9,362:
Disp {I,X}
Disp {I,X}
End
End
{A,B}</lang>
{A,B}</syntaxhighlight>
{{out}}
{{out}}
<pre>{171,125}</pre>
<pre>{171,125}</pre>
Line 9,368: Line 9,368:
=={{header|Transd}}==
=={{header|Transd}}==
{{trans|Python}}
{{trans|Python}}
<lang scheme>#lang transd
<syntaxhighlight lang="scheme">#lang transd


MainModule: {
MainModule: {
Line 9,393: Line 9,393:
)
)
)
)
}</lang>{{out}}
}</syntaxhighlight>{{out}}
<pre>
<pre>
Length of (27): 112
Length of (27): 112
Line 9,402: Line 9,402:


=={{header|TXR}}==
=={{header|TXR}}==
<lang txr>@(do (defun hailstone (n)
<syntaxhighlight lang="txr">@(do (defun hailstone (n)
(cons n
(cons n
(gen (not (eq n 1))
(gen (not (eq n 1))
Line 9,427: Line 9,427:
(set max len)
(set max len)
(set maxi i))))
(set maxi i))))
(format t "longest sequence is ~a for n = ~a\n" max maxi)))</lang>
(format t "longest sequence is ~a for n = ~a\n" max maxi)))</syntaxhighlight>


<pre>$ txr -l hailstone.txr
<pre>$ txr -l hailstone.txr
Line 9,434: Line 9,434:
=={{header|uBasic/4tH}}==
=={{header|uBasic/4tH}}==
{{Trans|FreeBASIC}}
{{Trans|FreeBASIC}}
<lang>' ------=< MAIN >=------
<syntaxhighlight lang="text">' ------=< MAIN >=------


m = 0
m = 0
Line 9,502: Line 9,502:
Loop
Loop


Return (b@)</lang>
Return (b@)</syntaxhighlight>
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.
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
{{out}}<pre>sequence for number 27
Line 9,528: Line 9,528:
The best way is to use a shell with built-in arrays and arithmetic, such as Bash.
The best way is to use a shell with built-in arrays and arithmetic, such as Bash.
{{works with|Bash}}
{{works with|Bash}}
<lang bash>#!/bin/bash
<syntaxhighlight lang="bash">#!/bin/bash
# seq is the array genereated by hailstone
# seq is the array genereated by hailstone
# index is used for seq
# index is used for seq
Line 9,564: Line 9,564:
done
done


echo "${max} has a hailstone sequence length of ${maxlen}"</lang>
echo "${max} has a hailstone sequence length of ${maxlen}"</syntaxhighlight>


{{out}}
{{out}}
Line 9,579: Line 9,579:


{{works with|Bourne Shell}}
{{works with|Bourne Shell}}
<lang bash># Outputs a hailstone sequence from $1, with one element per line.
<syntaxhighlight lang="bash"># Outputs a hailstone sequence from $1, with one element per line.
# Clobbers $n.
# Clobbers $n.
hailstone() {
hailstone() {
Line 9,608: Line 9,608:
i=`expr $i + 1`
i=`expr $i + 1`
done
done
echo "Hailstone sequence from $max has $maxlen elements."</lang>
echo "Hailstone sequence from $max has $maxlen elements."</syntaxhighlight>


==={{header|C Shell}}===
==={{header|C Shell}}===
Line 9,614: Line 9,614:
This script is '''slow''', but it can reach 100000, and a fast computer might run it in less than 15 minutes.
This script is '''slow''', but it can reach 100000, and a fast computer might run it in less than 15 minutes.


<lang csh># Outputs a hailstone sequence from !:1, with one element per line.
<syntaxhighlight lang="csh"># Outputs a hailstone sequence from !:1, with one element per line.
# Clobbers $n.
# Clobbers $n.
alias hailstone eval \''@ n = \!:1:q \\
alias hailstone eval \''@ n = \!:1:q \\
Line 9,664: Line 9,664:
@ i += 1
@ i += 1
end
end
echo "Hailstone sequence from $max has $maxlen elements."</lang>
echo "Hailstone sequence from $max has $maxlen elements."</syntaxhighlight>


{{out}}
{{out}}
Line 9,675: Line 9,675:
===Implementation===
===Implementation===
<b>hailstone.u</b>
<b>hailstone.u</b>
<lang ursa>import "math"
<syntaxhighlight lang="ursa">import "math"


def hailstone (int n)
def hailstone (int n)
Line 9,689: Line 9,689:
append n seq
append n seq
return seq
return seq
end hailstone</lang>
end hailstone</syntaxhighlight>


===Usage===
===Usage===
Line 9,713: Line 9,713:


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


Line 9,724: Line 9,724:
<
<
^T(@ixX take/$4; %nLP~~lrxPX; ^|TL/~& :/'...',' has length '--@h+ %nP+ length) hail 27,
^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></lang>
^|TL(~&,:/' has sequence length ') %nP~~ nleq$^&r ^(~&,length+ hail)* nrange/1 100000></syntaxhighlight>
The <code>hail</code> function computes the sequence as follows.
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.
* 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 9,747: Line 9,747:


=={{header|VBA}}==
=={{header|VBA}}==
{{trans|Phix}}<lang vb>Private Function hailstone(ByVal n As Long) As Collection
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function hailstone(ByVal n As Long) As Collection
Dim s As New Collection
Dim s As New Collection
s.Add CStr(n), CStr(n)
s.Add CStr(n), CStr(n)
Line 9,800: Line 9,800:
Next i
Next i
Debug.Print "The longest hailstone sequence under 100,000 is"; imax; "with"; hmax; "elements."
Debug.Print "The longest hailstone sequence under 100,000 is"; imax; "with"; hmax; "elements."
End Sub</lang>{{out}}<pre>hailstone(27) = 27, 82, 41, 124, ... 16, 8, 4, 2, 1
End Sub</syntaxhighlight>{{out}}<pre>hailstone(27) = 27, 82, 41, 124, ... 16, 8, 4, 2, 1
length = 112
length = 112
The longest hailstone sequence under 100,000 is 77031 with 351 elements.</pre>
The longest hailstone sequence under 100,000 is 77031 with 351 elements.</pre>


=={{header|VBScript}}==
=={{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
'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.
'"e" for the number elements.
Line 9,848: Line 9,848:
WScript.StdOut.WriteLine "Number less than 100k with the longest sequence: "
WScript.StdOut.WriteLine "Number less than 100k with the longest sequence: "
WScript.StdOut.WriteLine n_longest
WScript.StdOut.WriteLine n_longest
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 9,862: Line 9,862:
{{trans|PL/I}}
{{trans|PL/I}}
{{works with|Visual Basic|VB6 Standard}}
{{works with|Visual Basic|VB6 Standard}}
<lang vb>Option Explicit
<syntaxhighlight lang="vb">Option Explicit
Dim flag As Boolean ' true to print values
Dim flag As Boolean ' true to print values
Sub main()
Sub main()
Line 9,918: Line 9,918:
End If
End If
hailstones = p
hailstones = p
End Function 'hailstones</lang>
End Function 'hailstones</syntaxhighlight>
{{Out}}
{{Out}}
<pre>The sequence for 27 is: 27 82 41 124 ... 8 4 2 1
<pre>The sequence for 27 is: 27 82 41 124 ... 8 4 2 1
Line 9,926: Line 9,926:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2005+}}
{{works with|Visual Basic .NET|2005+}}
<lang vbnet>Module HailstoneSequence
<syntaxhighlight lang="vbnet">Module HailstoneSequence
Sub Main()
Sub Main()
' Checking sequence of 27.
' Checking sequence of 27.
Line 9,967: Line 9,967:
End Function
End Function


End Module</lang>
End Module</syntaxhighlight>


{{out}}
{{out}}
Line 9,977: Line 9,977:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|go}}
{{trans|go}}
<lang vlang>// 1st arg is the number to generate the sequence for.
<syntaxhighlight lang="vlang">// 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
// 2nd arg is a slice to recycle, to reduce garbage.
fn hs(nn int, recycle []int) []int {
fn hs(nn int, recycle []int) []int {
Line 10,007: Line 10,007:
}
}
println("hs($max_n): $max_len elements")
println("hs($max_n): $max_len elements")
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>hs(27): 112 elements: [27 82 41 124 ... 8 4 2 1]
<pre>hs(27): 112 elements: [27 82 41 124 ... 8 4 2 1]
Line 10,013: Line 10,013:


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var hailstone = Fn.new { |n|
<syntaxhighlight lang="ecmascript">var hailstone = Fn.new { |n|
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
var h = [n]
var h = [n]
Line 10,041: Line 10,041:
}
}
System.print(" Longest = %(longest)")
System.print(" Longest = %(longest)")
System.print(" Length = %(longlen)")</lang>
System.print(" Length = %(longlen)")</syntaxhighlight>


{{out}}
{{out}}
Line 10,056: Line 10,056:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int Seq(1000); \more than enough for longest sequence
int Seq(1000); \more than enough for longest sequence


Line 10,085: Line 10,085:
];
];
IntOut(0, SN); Text(0, "'s Hailstone length = "); IntOut(0, MaxLen);
IntOut(0, SN); Text(0, "'s Hailstone length = "); IntOut(0, MaxLen);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 10,098: Line 10,098:
===Show The Sequence with n=27===
===Show The Sequence with n=27===
Output is in hexadecimal but is otherwise correct.
Output is in hexadecimal but is otherwise correct.
<lang z80>;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
<syntaxhighlight lang="z80">;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
read "\SrcCPC\MemoryMap.asm"
Line 10,244: Line 10,244:


HailstoneBuffer:
HailstoneBuffer:
ds 512,0</lang>
ds 512,0</syntaxhighlight>


{{out}}
{{out}}
Line 10,267: Line 10,267:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z);
<syntaxhighlight 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)) }</lang>
if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,z)) }</syntaxhighlight>
This uses tail recursion and thus is stack efficient.
This uses tail recursion and thus is stack efficient.
{{out}}
{{out}}
Line 10,281: Line 10,281:
</pre>
</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.
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.
<lang zkl>[2..0d100_000].pump(Void, // loop n from 2 to 100,000
<syntaxhighlight lang="zkl">[2..0d100_000].pump(Void, // loop n from 2 to 100,000
collatz, // generate Collatz sequence(n)
collatz, // generate Collatz sequence(n)
fcn(c,n){ // if new longest sequence, save length/C, return longest
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)))</lang>
if(c.len()>n[0]) n.clear(c.len(),c[0]); n}.fp1(L(0,0)))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 10,292: Line 10,292:
=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
{{trans|BBC_BASIC}}
<lang zxbasic>10 LET n=27: LET s=1
<syntaxhighlight lang="zxbasic">10 LET n=27: LET s=1
20 GO SUB 1000
20 GO SUB 1000
30 PRINT '"Sequence length = ";seqlen
30 PRINT '"Sequence length = ";seqlen
Line 10,312: Line 10,312:
1060 LET l=l+1
1060 LET l=l+1
1070 GO TO 1020
1070 GO TO 1020
2000 DEF FN m(a,b)=a-INT (a/b)*b</lang>
2000 DEF FN m(a,b)=a-INT (a/b)*b</syntaxhighlight>