Hailstone sequence: Difference between revisions

add ABC
(add ABC)
 
(36 intermediate revisions by 23 users not shown)
Line 39:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F hailstone(=n)
V seq = [n]
L n > 1
Line 50:
 
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]))</langsyntaxhighlight>
 
{{out}}
Line 58:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Hailstone sequence 16/08/2015
HAILSTON CSECT
USING HAILSTON,R12
Line 160:
XDEC DS CL12
YREGS
END HAILSTON</langsyntaxhighlight>
{{out}}
<pre>
Line 168:
 
=={{header|ABAP}}==
<syntaxhighlight lang="abap">
<lang ABAP>
CLASS lcl_hailstone DEFINITION.
PUBLIC SECTION.
Line 258:
cl_demo_output=>write( lcl_hailstone=>get_longest_sequence_upto( 100000 ) ).
cl_demo_output=>display( ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 275:
</pre>
 
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO RETURN hailstone n:
PUT {} IN seq
WHILE 1=1:
PUT n IN seq[#seq]
SELECT:
n=1: RETURN seq
n mod 2=0: PUT floor(n/2) IN n
n mod 2=1: PUT 3*n+1 IN n
RETURN seq
 
PUT hailstone 27 IN h27
WRITE "Length of Hailstone sequence for 27:", #h27/
WRITE "First 4 elements:", h27[0], h27[1], h27[2], h27[3]/
WRITE "Last 4 elements:", h27[#h27-4], h27[#h27-3], h27[#h27-2], h27[#h27-1]/
 
PUT 0, 0 IN longest, length
FOR n IN {1..100000}:
PUT hailstone n IN hn
IF #hn > length:
PUT n, #hn IN longest, length
 
WRITE longest, "has the longest hailstone sequence < 100,000, of length:", length/</syntaxhighlight>
{{out}}
<pre>Length of Hailstone sequence for 27: 112
First 4 elements: 27 82 41 124
Last 4 elements: 8 4 2 1
77031 has the longest hailstone sequence < 100,000, of length: 351</pre>
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun hailstone (len)
(loop for x = len
then (if (evenp x)
Line 291 ⟶ 319:
(if (> new-mx mx)
(max-hailstone-start (1- limit) new-mx limit)
(max-hailstone-start (1- limit) mx curr)))))</langsyntaxhighlight>
 
{{out}}
Line 305 ⟶ 333:
=={{header|Ada}}==
Similar to [[#C|C method]]:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
procedure hailstone is
type int_arr is array(Positive range <>) of Integer;
Line 343 ⟶ 371:
end loop;
put_line(Integer'Image(nmax)&" max @ n= "&Integer'Image(stonemax));
end hailstone;</langsyntaxhighlight>
{{out}}
<pre>
Line 355 ⟶ 383:
 
hailstones.ads:
<langsyntaxhighlight Adalang="ada">package Hailstones is
type Integer_Sequence is array(Positive range <>) of Integer;
function Create_Sequence (N : Positive) return Integer_Sequence;
end Hailstones;</langsyntaxhighlight>
hailstones.adb:
<langsyntaxhighlight Adalang="ada">package body Hailstones is
function Create_Sequence (N : Positive) return Integer_Sequence is
begin
Line 374 ⟶ 402:
end if;
end Create_Sequence;
end Hailstones;</langsyntaxhighlight>
example main.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
with Hailstones;
 
Line 418 ⟶ 446:
Ada.Text_IO.Put_Line ("with N =" & Integer'Image (Longest_N));
end;
end Main;</langsyntaxhighlight>
{{out}}
<pre>Length of 27: 112
Line 427 ⟶ 455:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
print_hailstone(integer h)
{
Line 484 ⟶ 512:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>hailstone sequence for 27 is 27 82 41 124 .. 8 4 2 1, it is 112 long
Line 491 ⟶ 519:
=={{header|ALGOL 60}}==
{{works with|A60}}
<langsyntaxhighlight lang="algol60">begin
comment Hailstone sequence - Algol 60;
integer array collatz[1:400]; integer icollatz;
Line 533 ⟶ 561:
outstring(1,", with"); outinteger(1,nel); outstring(1,"elements.");
outstring(1,"\n")
end </langsyntaxhighlight>
{{out}}
<pre>
Line 549 ⟶ 577:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - using the ''print'' routine rather than ''printf''}}
<langsyntaxhighlight lang="algol68">MODE LINT = # LONG ... # INT;
 
PROC hailstone = (INT in n, REF[]LINT array)INT:
Line 595 ⟶ 623:
print(("Max",hmax," at j=",jatmax, new line))
#
)</langsyntaxhighlight>
{{out}}
<pre>
Line 605 ⟶ 633:
=={{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.
<langsyntaxhighlight lang="algol">
BEGIN
 
Line 665 ⟶ 693:
WRITE("MAXIMUM SEQUENCE LENGTH =", LONGEST, " FOR N =", NLONG);
 
END </langsyntaxhighlight>
{{out}}
<pre>
Line 688 ⟶ 716:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% show some Hailstone Sequence related information %
% calculates the length of the sequence generated by n, %
Line 762 ⟶ 790:
end
end
end.</langsyntaxhighlight>
{{out}}
<pre>
27: length 112, first: [27 82 41 124] last: [8 4 2 1]
Maximum sequence length: 351 for: 77031
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
#include <basico.h>
 
#proto Hailstone(_X_,_SW_)
 
algoritmo
 
valor=27, máxima secuencia=0, vtemp=0
imprimir ( _Hailstone(27,1) ---copiar en 'máxima secuencia'--- , NL )
i=28
iterar
_Hailstone(i,0), copiar en 'vtemp'
cuando( sea mayor que 'máxima secuencia' ) {
máxima secuencia = vtemp
valor=i
}
++i
hasta que ' #(i==100000) '
imprimir ( #(utf8("Máxima longitud ")),máxima secuencia,\
" fue encontrada para Hailstone(",valor,\
#(utf8(") para números <100,000")), NL )
 
terminar
 
subrutinas
 
Hailstone(n, sw)
largo_de_secuencia = 0
v={}, n, mete(v)
iterar
tomar si ( es par(n), #(n/2), \
tomar si ( #(n<>1), #(3*n+1), 1) )
---copiar en 'n'--- mete(v)
hasta que ' #(n==1) '
#(length(v)), mover a 'largo_de_secuencia'
cuando (sw){
decimales '0'
#( v[1:4] ), ",...,",
#( v[largo_de_secuencia-4 : largo_de_secuencia] )
NL, #(utf8("Tamaño de la secuencia: "))
imprime esto; decimales normales
}
retornar ' largo_de_secuencia '
 
</syntaxhighlight>
{{out}}
<pre>
27,82,41,124,...,16,8,4,2,1
Tamaño de la secuencia: 112
Máxima longitud 351 fue encontrada para Hailstone(77031) para números <100,000
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">
<lang APL>
⍝ recursive dfn:
dfnHailstone←{
Line 791 ⟶ 873:
 
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight APLlang="apl"> dfnHailstone 5
5 16 8 4 2 1
5↑hailstone 27
Line 802 ⟶ 884:
112
1↑{⍵[⍒↑(⍴∘hailstone)¨⍵]}⍳100000
77031</langsyntaxhighlight>
 
=={{header|AppleScript}}==
 
<langsyntaxhighlight lang="applescript">on hailstoneSequence(n)
script o
property sequence : {n}
Line 826 ⟶ 908:
tell hailstoneSequence(n)
return {n:n, |length of sequence|:(its length), |first 4 numbers|:items 1 thru 4, |last 4 numbers|:items -4 thru -1}
end tell</langsyntaxhighlight>
 
{{output}}
<pre>{|length of sequence|:112, |first 4 numbers|:{27, 82, 41, 124}, |last 4 numbers|:{8, 4, 2, 1}}</pre>
 
<langsyntaxhighlight lang="applescript">-- Number(s) below 100,000 giving the longest sequence length, using the hailstoneSequence(n) handler above.
set nums to {}
set longestLength to 1
Line 843 ⟶ 925:
set end of nums to n
end if
end repeat</lang>
return {|number(s) giving longest sequence length|:nums, |length of sequence|:longestLength}</syntaxhighlight>
 
{{output}}
Line 855 ⟶ 938:
===Hailstone Sequence of N equal to 27 ===
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly"> .org 0x08000000
 
b ProgramStart
Line 1,004 ⟶ 1,087:
;;;;;;;;;;; EVERYTHING PAST THIS POINT IS JUST I/O ROUTINES FOR PRINTING NUMBERS AND WORDS TO THE GAME BOY ADVANCE'S SCREEN
;;;;;;;;;;; I ASSURE YOU THAT ALL OF IT WORKS BUT CHANCES ARE YOU DIDN'T COME HERE TO SEE THAT.
;;;;;;;;;;; THANKS TO KEITH OF CHIBIAKUMAS.COM FOR WRITING THEM!</langsyntaxhighlight>
 
{{out}}
Line 1,033 ⟶ 1,116:
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:
 
<langsyntaxhighlight ARMlang="arm Assemblyassembly"> mov r0,#1
bl Hailstone
mov r6,r3
Line 1,071 ⟶ 1,154:
mov r0,r6
bl ShowHex32
bl NewLine</langsyntaxhighlight>
 
{{out}}
Line 1,087 ⟶ 1,170:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">hailstone: function [n][
ret: @[n]
while [n>1][
Line 1,113 ⟶ 1,196:
 
print ["max hailstone sequence found (<100000): of length" maxHailstoneLength "for" maxHailstone]
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,123 ⟶ 1,206:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">; Submitted by MasterFocus --- http://tiny.cc/iTunis
 
; [1] Generate the Hailstone Seq. for a number
Line 1,162 ⟶ 1,245:
}
ToolTip
MsgBox % "Number: " MaxNum "`nCount: " Max</langsyntaxhighlight>
 
=={{header|AutoIt}}==
 
 
<langsyntaxhighlight lang="autoit">
$Hail = Hailstone(27)
ConsoleWrite("Sequence-Lenght: "&$Hail&@CRLF)
Line 1,196 ⟶ 1,279:
Return $Counter
EndFunc ;==>Hailstone
</syntaxhighlight>
</lang>
{{out}}
<pre>27,82,41,124,62,31,94,47,142,71,214,107,322,161,484,242,121,364,182,91,274,137,412,206,103,
Line 1,208 ⟶ 1,291:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">
#!/usr/bin/awk -f
function hailstone(v, verbose) {
Line 1,238 ⟶ 1,321:
printf("longest hailstone sequence is %i and has %i elements\n",ix,m);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,248 ⟶ 1,331:
=={{header|BASIC}}==
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight ApplesoftBasiclang="applesoftbasic">10 HOME
 
100 N = 27
Line 1,279 ⟶ 1,362:
470 IF EVEN THEN N=N/2
480 IF NOT EVEN THEN N = (3 * N) + 1
490 NEXT L : STOP</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> seqlen% = FNhailstone(27, TRUE)
PRINT '"Sequence length = "; seqlen%
maxlen% = 0
Line 1,304 ⟶ 1,387:
L% += 1
ENDWHILE
= L% + 1</langsyntaxhighlight>
{{out}}
<pre>
Line 1,328 ⟶ 1,411:
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight QBASIClang="qbasic">100 PRINT : PRINT "HAILSTONE SEQUENCE FOR N = 27:"
110 N=27 : SHOW=1
120 GOSUB 1000
Line 1,351 ⟶ 1,434:
1060 S = 3*S+1
1070 GOTO 1020
</syntaxhighlight>
</lang>
==={{header|FreeBASIC}}===
<langsyntaxhighlight FreeBASIClang="freebasic">' version 17-06-2015
' compile with: fbc -s console
 
Line 1,443 ⟶ 1,526:
Print : Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>sequence for number 27
Line 1,464 ⟶ 1,547:
 
==={{header|GW-BASIC}}===
<langsyntaxhighlight lang="gwbasic">10 N# = 27
20 P = 1
30 GOSUB 130
Line 1,481 ⟶ 1,564:
160 IF N#/2 = INT(N#/2) THEN N# = N#/2 ELSE N# = 3*N# + 1
170 C = C + 1
180 GOTO 140</langsyntaxhighlight>
 
==={{header|Liberty BASIC}}===
<langsyntaxhighlight lang="lb">print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
while hailstone < 1 or hailstone <> int(hailstone)
Line 1,535 ⟶ 1,618:
print ""
print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"."
end</langsyntaxhighlight>
 
==={{header|OxygenBasic}}===
<langsyntaxhighlight lang="oxygenbasic">
 
function Hailstone(sys *n)
Line 1,577 ⟶ 1,660:
 
'result 100000, 77031, 351
</syntaxhighlight>
</lang>
 
==={{header|PureBasic}}===
<langsyntaxhighlight PureBasiclang="purebasic">NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array
 
Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list
Line 1,627 ⟶ 1,710:
Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
{{out}}
Line 1,658 ⟶ 1,741:
 
==={{header|Run BASIC}}===
<langsyntaxhighlight lang="runbasic">print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
Line 1,697 ⟶ 1,780:
end if
wend
END FUNCTION</langsyntaxhighlight>
 
==={{header|Tiny BASIC}}===
Tiny BASIC is limited to signed integers from -32768 to 32767. This code combines two integers into one: number = 32766A + B, to emulate integers up to 1.07 billion. Dealing with integer truncation, carries, and avoiding overflows requires some finesse. Even so one number, namely 77671, causes an overflow because one of its steps exceeds 1.07 billion.
 
<syntaxhighlight lang="text"> PRINT "Enter a positive integer"
INPUT N REM unit column
LET M = 0 REM 32766 column
Line 1,770 ⟶ 1,853:
PRINT "at step number ",C
PRINT "trying to triple 32766x",M," + ",N
RETURN</langsyntaxhighlight>
{{out}}
<pre>
Line 1,793 ⟶ 1,876:
''2. Show that the hailstone sequence for the number 27 has 112 elements... ''
<!--The third task is NOT included because task #3 will take several hours in processing...-->
<langsyntaxhighlight lang="dos">@echo off
setlocal enabledelayedexpansion
echo.
Line 1,833 ⟶ 1,916:
set /a num/=2
set seq=!seq! %num%
goto loop</langsyntaxhighlight>
{{Out}}
<pre>Task #1: (Start:111)
Line 1,846 ⟶ 1,929:
 
The script above could only be used in '''smaller''' inputs. Thus, for the third task, a slightly different script will be used. However, this script is still '''slow'''. I tried this on a fast computer and it took about 40-45 minutes to complete.
<langsyntaxhighlight lang="dos">@echo off
setlocal enableDelayedExpansion
if "%~1"=="test" (
Line 1,868 ⟶ 1,951:
pause>nul
 
exit /b 0</langsyntaxhighlight>
{{Out}}
<pre>Number less than 100000 with longest sequence: 77031
Line 1,879 ⟶ 1,962:
'''The pure hailstone sequence function''', returning the sequence for any number entered in the console:
 
<langsyntaxhighlight lang="beeswax"> >@:N q
>%"d3~@.PNp
d~2~pL~1F{<T_</langsyntaxhighlight>
 
'''Returning the sequence for the starting value <code>27</code>'''
 
<langsyntaxhighlight lang="beeswax"> >@:N q
>%"d3~@.PNq
d~2~qL~1Ff{<BF3_
{NNgA<</langsyntaxhighlight>
 
Output of the sequence, followed by the length of the sequence:
 
<syntaxhighlight lang="text">
27
82
Line 1,922 ⟶ 2,005:
1
 
112</langsyntaxhighlight>
 
'''Number below 100,000 with the longest hailstone sequence, and the length of that sequence:'''
 
<langsyntaxhighlight lang="beeswax"> >@: q pf1_#
>%"d3~@.Pqf#{g?` `{gpK@~BP9~5@P@q'M<
d~2~pL~1Ff< < >?d
>zAg?MM@1~y@~gLpz2~yg@~3~hAg?M d
>?~fz1~y?yg@hhAg?Mb</langsyntaxhighlight>
 
Output:
 
<syntaxhighlight lang="text">77031 351</langsyntaxhighlight>
 
=={{header|Befunge}}==
<langsyntaxhighlight lang="befunge">93*:. v
> :2%v >
v+1*3_2/
Line 1,955 ⟶ 2,038:
vg01g00 ,+49<
>"@"*+.@
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,965 ⟶ 2,048:
=={{header|BQN}}==
Works in: [[CBQN]]
<langsyntaxhighlight lang="bqn">Collatz ← ⥊⊸{
𝕨𝕊1: 𝕨;
(𝕨⊸∾ 𝕊 ⊢) (2|𝕩)⊑⟨𝕩÷2⋄1+3×𝕩⟩
Line 1,977 ⟶ 2,060:
•Show Collatz1 5
 
•Show (⊑∾≠){𝕩⊑˜⊑⍒≠¨𝕩}Collatz1¨1+↕99999</langsyntaxhighlight>
<langsyntaxhighlight lang="bqn">⟨ 5 16 8 4 2 1 ⟩
⟨ 77031 351 ⟩</langsyntaxhighlight>
 
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat">(
( hailstone
= L len
Line 2,024 ⟶ 2,107:
)
)
);</langsyntaxhighlight>
 
=={{header|Brainf***}}==
{{incomplete}}
<langsyntaxhighlight Brainflang="brainf***">>>>>>>,>,>,<<
 
[
Line 2,110 ⟶ 2,193:
[Cell 16: ASCII code for " " (Space). ]
[Rest of the cells: Temp cells. ]
</syntaxhighlight>
</lang>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">hailstone = { num |
sequence = [num]
while { num != 1 }
Line 2,145 ⟶ 2,228:
}
 
p "Longest was starting from #{longest[:number]} and was of length #{longest[:length]}"</langsyntaxhighlight>
{{out}}
<pre>Sequence for 27 is correct
Line 2,155 ⟶ 2,238:
Longest so far: 77031 @ 351 elements
Longest was starting from 77031 and was of length 351</pre>
 
=={{header|Bruijn}}==
 
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/List .
:import std/Math M
:import std/Number/Binary .
 
# hailstone sequence using binary shifts
hailstone y [[(0 =? (+1b)) {}0 go]]
go 0 : (=²?0 (1 /²0) (1 (↑¹0 + 0)))
 
# --- tests ---
 
seq-27 hailstone (+27b)
 
:test (∀seq-27) ((+112))
:test (take (+4) seq-27) ((+27b) : ((+82b) : ((+41b) : {}(+124b))))
:test (take (+4) <~>seq-27) ((+1b) : ((+2b) : ((+4b) : {}(+8b))))
 
below-100000 [0 : ∀(hailstone 0)] <$> seq
seq take (+99999) (iterate ++‣ (+1b))
 
main [head (max-by (M.compare ⋔ tail) below-100000)]
</syntaxhighlight>
 
=={{header|Burlesque}}==
 
<langsyntaxhighlight lang="burlesque">
blsq ) 27{^^^^2.%{3.*1.+}\/{2./}\/ie}{1!=}w!bx{\/+]}{\/isn!}w!L[
112
</syntaxhighlight>
</lang>
 
=={{header|C}}==
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 2,204 ⟶ 2,313:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>[ 27, 82, 41, 124, ...., 8, 4, 2, 1] len= 112
Line 2,211 ⟶ 2,320:
===With caching===
Much faster if you want to go over a million or so.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
#define N 10000000
Line 2,241 ⟶ 2,350:
printf("max below %d: %d, length %d\n", N, mi, max);
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 2,287 ⟶ 2,396:
}
}
}</langsyntaxhighlight>
<pre>
112 Elements
Line 2,296 ⟶ 2,405:
===With caching===
As with the [[#C|C example]], much faster if you want to go over a million or so.
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 2,337 ⟶ 2,446:
}
}
}</langsyntaxhighlight>
<pre>
max below 100000: 77031 (351 steps)
Line 2,343 ⟶ 2,452:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <vector>
#include <utility>
Line 2,392 ⟶ 2,501:
 
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 2,404 ⟶ 2,513:
{{uses from|library|Qt}}
Templated solution works for all of Qt's sequential container classes (QLinkedList, QList, QVector).
<langsyntaxhighlight lang="cpp">
#include <QDebug>
#include <QVector>
Line 2,443 ⟶ 2,552:
qInfo() << " starting element:" << max.first();
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,456 ⟶ 2,565:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
{Integer*} hailstone(variable Integer n) {
Line 2,478 ⟶ 2,587:
}
print("the longest sequence under 100,000 starts with ``longest.first else "what?"`` and has length ``longest.size``");
}</langsyntaxhighlight>
 
=={{header|CLIPS}}==
<langsyntaxhighlight lang="clips">(deftemplate longest
(slot bound) ; upper bound for the range of values to check
(slot next (default 2)) ; next value that needs to be checked
Line 2,556 ⟶ 2,665:
(printout t "sequence is " ?start " with a length of " ?len "." crlf)
(printout t crlf)
)</langsyntaxhighlight>
 
{{out}}
Line 2,568 ⟶ 2,677:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(defn hailstone-seq [n]
{:pre [(pos? n)]}
(lazy-seq
Line 2,584 ⟶ 2,693:
(for [i (range 1 100000)]
{:num i, :len (count (hailstone-seq i))}))]
(println "Maximum length" max-len "was found for hailstone(" max-i ")."))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Generate the hailstone sequence for a number
hailstone = iter (n: int) yields (int)
while true do
Line 2,641 ⟶ 2,750:
|| " has the longest hailstone sequence < 100000: "
|| int$unparse(maxlen))
end start_up</langsyntaxhighlight>
{{out}}
<pre>The hailstone sequence for 27 has 112 elements.
Line 2,649 ⟶ 2,758:
=={{header|COBOL}}==
Testing with GnuCOBOL
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. hailstones.
remarks. cobc -x hailstones.cob.
Line 2,738 ⟶ 2,847:
.
 
end program hailstones.</langsyntaxhighlight>
 
{{out}}
Line 2,753 ⟶ 2,862:
=={{header|CoffeeScript}}==
Recursive version:
<langsyntaxhighlight lang="coffeescript">hailstone = (n) ->
if n is 1
[n]
Line 2,778 ⟶ 2,887:
maxnums = [i]
console.log "Max length: #{maxlength}; numbers generating sequences of this length: #{maxnums}"</langsyntaxhighlight>
<pre>hailstone(27) = 27,82,41,124 ... 8,4,2,1 (length: 112)
Max length: 351; numbers generating sequences of this length: 77031</pre>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun hailstone (n)
(cond ((= n 1) '(1))
((evenp n) (cons n (hailstone (/ n 2))))
Line 2,793 ⟶ 2,902:
(let ((len (length (hailstone i))))
(when (> len l) (setq l len k i)))
finally (format t "Longest hailstone sequence under ~A for ~A, having length ~A." n k l))))</langsyntaxhighlight>
Sample session:
<pre>ROSETTA> (length (hailstone 27))
Line 2,806 ⟶ 2,915:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
# Generate the hailstone sequence for the given N and return the length.
Line 2,868 ⟶ 2,977:
print(" has the longest hailstone sequence < 100000: ");
print_i32(max_len);
print_nl();</langsyntaxhighlight>
 
{{out}}
Line 2,876 ⟶ 2,985:
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
def hailstone(n)
seq = [n]
Line 2,894 ⟶ 3,003:
puts ([twenty_seven.size, twenty_seven.first(4), max.last(4)])
# => [112, [27, 82, 41, 124], [8, 4, 2, 1]]
</syntaxhighlight>
</lang>
 
=={{header|D}}==
===Basic Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;
 
auto hailstone(uint n) pure nothrow {
Line 2,920 ⟶ 3,029:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
{{out}}
<pre>hailstone(27)= [27, 82, 41, 124] ... [8, 4, 2, 1]
Line 2,928 ⟶ 3,037:
===Lazy Version===
Same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.typecons, std.range;
 
auto hailstone(uint m) pure nothrow @nogc {
Line 2,947 ⟶ 3,056:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
===Faster Lazy Version===
Same output.
<langsyntaxhighlight lang="d">struct Hailstone {
uint n;
bool empty() const pure nothrow @nogc { return n == 0; }
Line 2,973 ⟶ 3,082:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
===Lazy Version With Caching===
Faster, same output.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;
 
struct Hailstone(size_t cacheSize = 500_000) {
Line 3,009 ⟶ 3,118:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
===Generator Range Version===
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons, std.concurrency;
 
auto hailstone(size_t n) {
Line 3,035 ⟶ 3,144:
.reduce!max;
writeln("Longest sequence in [1,", N, "]= ",p[1]," with len ",p[0]);
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<syntaxhighlight lang="dart">
<lang dart>List<int> hailstone(int n) {
import 'package:collection/collection.dart';
if(n<=0) {
import 'dart:collection';
throw new IllegalArgumentException("start value must be >=1)");
List<int> hailstone(int n) {
if(n <= 0) {
throw ArgumentError("start value must be >=1)");
}
Queue<int>var seq =new Queue<int>();
seq.add(n);
while(n != 1) {
n = n%2 == 0 ?( n ~/ 2).toInt() : 3 * n + 1;
seq.add(n);
}
return new List<int>seq.fromtoList(seq);
}
 
// apparently List is missing toString()
String iterableToString(Iterable seq) {
String str="[";
Iterator i=seq.iterator();
while(i.hasNext()) {
str+=i.next();
if(i.hasNext()) {
str+=",";
}
}
return str+"]";
}
 
main() {
for(int i = 1; i <= 10; i++) {
print("h($i) ="+iterableToString( ${hailstone(i))}");
}
List<int>var h27 = hailstone(27);
List<int>var first4 = h27.getRangetake(0,4).toList();
print("first 4 elements of h(27): "+iterableToString($first4)");
Expectassert(ListEquality().listEqualsequals([27, 82, 41, 124], first4));
 
List<int>var last4 = h27.getRangeskip(h27.length - 4,).take(4).toList();
print("last 4 elements of h(27): "+iterableToString($last4)");
Expectassert(ListEquality().listEqualsequals([8, 4, 2, 1], last4));
 
print("length of sequence h(27): "+${h27.length}");
Expect.equalsassert(112, == h27.length);
 
int seq = 0, max = 0;
for(int i = 1; i <= 100000; i++) {
List<int>var h = hailstone(i);
if(h.length > max) {
max = h.length;
seq = i;
}
}
print("up to 100000 the sequence h($seq) has the largest length ($max)");
}
}</lang>
</syntaxhighlight>
{{out}}
<pre>h(1) = [1]
h(2) = [2, 1]
h(3) = [3, 10, 5, 16, 8, 4, 2, 1]
h(4) = [4, 2, 1]
h(5) = [5, 16, 8, 4, 2, 1]
h(6) = [6, 3, 10, 5, 16, 8, 4, 2, 1]
h(7) = [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
h(8) = [8, 4, 2, 1]
h(9) = [9, 28, 14, 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1]
h(10) = [10, 5, 16, 8, 4, 2, 1]
first 4 elements of h(27): [27, 82, 41, 124]
last 4 elements of h(27): [8, 4, 2, 1]
length of sequence h(27): 112
up to 100000 the sequence h(77031) has the largest length (351)</pre>
Line 3,111 ⟶ 3,211:
The e and o procedure is for even and odd number respectively.
The x procedure is for overall control.
<syntaxhighlight lang="dc">27
<lang Dc>27
[[--: ]nzpq]sq
[d 2/ p]se
[d 3*1+ p]so
[d2% 0=e d1=q d2% 1=o d1=q lxx]dsxx</langsyntaxhighlight>
{{out}}
<pre>
Line 3,133 ⟶ 3,233:
Register L for the length of the longest sequence and T for the corresponding number.
Also, procedure q is slightly modified for storing L and T if needed, and all printouts in procedure e and o are muted.
<langsyntaxhighlight Dclang="dc">0dsLsT1st
[dsLltsT]sM
[[zdlL<M q]sq
Line 3,141 ⟶ 3,241:
[lt1+dstlsxc lt100000>l]dslx
lTn[:]nlLp
</syntaxhighlight>
</lang>
{{out}} (Takes quite some time on a decent machine)
<pre>77031:351</pre>
 
=={{header|DCL}}==
<langsyntaxhighlight DCLlang="dcl">$ n = f$integer( p1 )
$ i = 1
$ loop:
Line 3,168 ⟶ 3,268:
$ write sys$output "sequence has ", i, " elements starting with ", s1, ", ", s2, ", ", s3, ", ", s4, " and ending with ", s'preantepenultimate_i, ", ", s'antepenultimate_i, ", ", s'penultimate_i, ", ", s'i
$ endif
$ sequence_length == i</langsyntaxhighlight>
{{out}}
<pre>$ @hailstone 27
sequence has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1</pre>
<langsyntaxhighlight DCLlang="dcl">$ limit = f$integer( p1 )
$ i = 1
$ max_so_far = 0
Line 3,212 ⟶ 3,312:
$ sequence_length == I
$ exit
$ endsubroutine</langsyntaxhighlight>
{{out}}
<pre>$ @longest_hailstone 100000
Line 3,221 ⟶ 3,321:
=== Using List<Integer> ===
 
<langsyntaxhighlight Delphilang="delphi">program ShowHailstoneSequence;
 
{$APPTYPE CONSOLE}
Line 3,277 ⟶ 3,377:
 
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>27: 112 elements
Line 3,292 ⟶ 3,392:
{{libheader| Boost.Int}}[https://github.com/MaiconSoft/DelphiBoostLib]
{{libheader| System.Diagnostics}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program ShowHailstoneSequence;
 
Line 3,345 ⟶ 3,445:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,356 ⟶ 3,456:
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local hailstone:
swap [ over ]
while < 1 dup:
Line 3,391 ⟶ 3,491:
!print( "number: " to-str max ", length: " to-str maxlen )
else:
@hailstone</langsyntaxhighlight>
{{out}}
<pre>true
Line 3,403 ⟶ 3,503:
true
number: 77031, length: 351</pre>
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
proc hailstone n . list[] .
list[] = [ ]
while n <> 1
list[] &= n
if n mod 2 = 0
n = n / 2
else
n = 3 * n + 1
.
.
list[] &= 1
.
hailstone 27 l[]
write "27 has length " & len l[] & " with "
for i to 4
write l[i] & " "
.
write "... "
for i = len l[] - 3 to len l[]
write l[i] & " "
.
print ""
for i = 1 to 100000
hailstone i l[]
if len l[] >= max_iter
max_i = i
max_iter = len l[]
end
end
print max_i & " has length " & max_iter
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'hash)
(lib 'sequences)
Line 3,435 ⟶ 3,569:
(writeln 'maxlength= hmaxlength 'for hmaxseed))
 
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(define H27 (iterator/f hailstone 27))
(take H27 6)
Line 3,471 ⟶ 3,605:
maxlength= 525 for 837799
 
</syntaxhighlight>
</lang>
 
=={{header|EDSAC order code}}==
Line 3,477 ⟶ 3,611:
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.
<langsyntaxhighlight lang="edsac">
[Hailstone (or Collatz) task for Rosetta Code.
EDSAC program, Initial Orders 2.]
Line 3,738 ⟶ 3,872:
E 41 Z [define entry point]
P F [acc = 0 on entry]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,752 ⟶ 3,886:
 
=={{header|Egel}}==
<syntaxhighlight lang="egel">
<lang Egel>
import "prelude.eg"
 
Line 3,795 ⟶ 3,929:
 
def main = (task0, task1, task2)
</syntaxhighlight>
</lang>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 3,866 ⟶ 4,000:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,876 ⟶ 4,010:
 
=={{header|Elena}}==
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'collections;
import extensions;
Line 3,915 ⟶ 4,049:
auto recursiveLengths := new Map<int,int>(4096,4096);
for(int i := 1,; i < maxNumber,; i+=1)
{
var chainLength := Hailstone(i, recursiveLengths);
Line 3,926 ⟶ 4,060:
console.printFormatted("max below {0}: {1} ({2} steps)", maxNumber, longestNumber, longestChain)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,933 ⟶ 4,067:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Hailstone do
require Integer
Line 3,955 ⟶ 4,089:
end
 
Hailstone.run</langsyntaxhighlight>
 
{{out}}
Line 3,961 ⟶ 4,095:
Hailstone(27) has 112 elements: [27, 82, 41, 124, ..., 8, 4, 2, 1]
Longest sequence starting under 100000 begins with 77031 and has 351 elements.
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun hailstone = List by int n
List h = int[n]
while n != 1
n = when((n % 2 == 0), n / 2, 3 * n + 1)
h.append(n)
end
return h
end
int NUMBER = 27
int LESS_THAN = 100000
List sequence = hailstone(NUMBER)
writeLine("The hailstone sequence for the number " + NUMBER +
" has " + sequence.length + " elements")
writeLine("starting with " +
sequence.extractStart(4).join(", ") + " and ending with " +
sequence.extractEnd(4).join(", ") + ".")
int number = 0
sequence = int[]
for int i = 1; i < LESS_THAN; ++i
List current = hailstone(i)
if current.length > sequence.length
sequence = current
number = i
end
end
writeLine("The number less than 100000 with longest hailstone sequence is " +
number + ", with length of " + sequence.length + ".")
</syntaxhighlight>
{{out}}
<pre>
The hailstone sequence for the number 27 has 112 elements
starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1.
The number less than 100000 with longest hailstone sequence is 77031, with length of 351.
</pre>
 
=={{header|Erlang}}==
<langsyntaxhighlight lang="erlang">-module(hailstone).
-import(io).
-export([main/0]).
Line 3,987 ⟶ 4,158:
io:format("finding maximum hailstone(N) length for 1 <= N <= 100000..."),
{Length, N} = max_length(1, 100000),
io:format(" done.~nhailstone(~B) length: ~B~n", [N, Length]).</langsyntaxhighlight>
{{out}}
<pre>Eshell V5.8.4 (abort with ^G)
Line 4,006 ⟶ 4,177:
This version has one collatz function for just calculating totals (just for fun) and the second generating lists.
 
<langsyntaxhighlight lang="erlang">
-module(collatz).
-export([main/0,collatz/1,coll/1,max_atz_under/1]).
Line 4,035 ⟶ 4,206:
io:format("Max: ~w~n", [max_atz_under(100000)]),
io:format("Total: ~w~n", [ length( Seq1000 ) ] ).
</syntaxhighlight>
</lang>
'''Output'''
<pre>
Line 4,051 ⟶ 4,222:
=={{header|ERRE}}==
In Italy it's known also as "Ulam conjecture".
<syntaxhighlight lang="erre">
<lang ERRE>
PROGRAM ULAM
 
Line 4,082 ⟶ 4,253:
PRINT("Max. number is";NMAX;" with";MAX_COUNT;"elements")
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,114 ⟶ 4,285:
=={{header|Euler Math Toolbox}}==
 
<syntaxhighlight lang="euler math toolbox">
<lang Euler Math Toolbox>
>function hailstone (n) ...
$ v=[n];
Line 4,159 ⟶ 4,330:
351
77031
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function hailstone(atom n)
sequence s
s = {n}
Line 4,207 ⟶ 4,378:
 
printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",
{imax,max})</langsyntaxhighlight>
{{out}}
<pre>hailstone(27) =
Line 4,232 ⟶ 4,403:
Ezhil is a Tamil programming language, see [http://en.wikipedia.org/wiki/Ezhil_%28programming_language%29 | Wikipedia] entry.
 
<langsyntaxhighlight lang="src="Pythonpython"">
நிரல்பாகம் hailstone ( எண் )
பதிப்பி "=> ",எண் #hailstone seq
Line 4,253 ⟶ 4,424:
பதிப்பி "**********************************************"
முடி
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let rec hailstone n = seq {
match n with
| 1 -> yield 1
Line 4,269 ⟶ 4,440:
 
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</langsyntaxhighlight>
{{out}}
<pre>Maximum length 351 was found for hailstone(77031)</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone
Line 4,304 ⟶ 4,475:
PRIVATE>
 
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>$ ./factor -run=rosetta.hailstone
Line 4,315 ⟶ 4,486:
 
=={{header|FALSE}}==
<langsyntaxhighlight lang="false">[$1&$[%3*1+0~]?~[2/]?]n:
[[$." "$1>][n;!]#%]s:
[1\[$1>][\1+\n;!]#%]c:
Line 4,322 ⟶ 4,493:
0m:0f:
1[$100000\>][$c;!$m;>[m:$f:0]?%1+]#%
f;." has hailstone sequence length "m;.</langsyntaxhighlight>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">Array g[2]
 
Func Collatz(n, d) =
Line 4,350 ⟶ 4,521:
g[1]:=champ;
g[2]:=record;
.</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: hail-next ( n -- n )
dup 1 and if 3 * 1+ else 2/ then ;
: .hail ( n -- )
Line 4,371 ⟶ 4,542:
swap . ." has hailstone sequence length " . ;
 
100000 longest-hail</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">program Hailstone
implicit none
 
Line 4,423 ⟶ 4,594:
end subroutine
 
end program</langsyntaxhighlight>
{{out}}
<pre>
Line 4,436 ⟶ 4,607:
{{Works with|Frege|3.21.586-g026e8d7}}
 
<langsyntaxhighlight lang="frege">module Hailstone where
 
import Data.List (maximumBy)
Line 4,455 ⟶ 4,626:
let t4 = show $ drop (length h27 - 4) h27
putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4)
putStrLn $ show $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000]</langsyntaxhighlight>
 
{{out}}
Line 4,467 ⟶ 4,638:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
hailstone[n] :=
{
Line 4,498 ⟶ 4,669:
 
println["$longestN has length $longestLen"]
</syntaxhighlight>
</lang>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">def
hailstone( 1 ) = [1]
hailstone( n ) = n # hailstone( if 2|n then n/2 else n*3 + 1 )
Line 4,511 ⟶ 4,682:
val (n, len) = maxBy( snd, [(i, hailstone( i ).length()) | i <- 1:100000] )
 
println( n, len )</langsyntaxhighlight>
 
{{out}}
Line 4,521 ⟶ 4,692:
=={{header|Futhark}}==
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun hailstone_step(x: int): int =
if (x % 2) == 0
Line 4,554 ⟶ 4,725:
(hailstone_seq x,
reduce max 0 (map hailstone_len (map (1+) (iota (n-1)))))
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
local fn Hailstone( n as NSInteger ) as NSInteger
NSInteger count = 1
while ( n != 1 )
if ( n and 1 ) == 1
n = n * 3 + 1
count++
end if
n = n / 2
count++
wend
end fn = count
 
 
 
void local fn PrintHailstone( n as NSInteger )
NSInteger count = 1, col = 1
print "Sequence for number "; n; ":" : print
print using "########"; n;
col = 2
while ( n != 1 )
if ( n and 1 ) == 1
n = n * 3 + 1
count++
else
n = n / 2
count++
end if
print using "########"; n;
if col == 10 then print : col = 1 else col++
wend
print : print
print "Sequence length = "; count
end fn
 
window 1, @"Hailstone Sequence", ( 0, 0, 620, 400 )
 
NSInteger n, seq_num, x, max_x, max_seq
 
seq_num = 27
 
print
fn PrintHailstone( seq_num )
print
 
for x = 1 to 100000
n = fn Hailstone( x )
if n > max_seq
max_x = x
max_seq = n
end if
next
 
print "The longest sequence is for "; max_x; ", it has a sequence length of "; max_seq; "."
 
HandleEvents
</syntaxhighlight>
 
{{output}}
<pre>
Sequence for number 27:
 
27 82 41 124 62 31 94 47 142 71
214 107 322 161 484 242 121 364 182 91
274 137 412 206 103 310 155 466 233 700
350 175 526 263 790 395 1186 593 1780 890
445 1336 668 334 167 502 251 754 377 1132
566 283 850 425 1276 638 319 958 479 1438
719 2158 1079 3238 1619 4858 2429 7288 3644 1822
911 2734 1367 4102 2051 6154 3077 9232 4616 2308
1154 577 1732 866 433 1300 650 325 976 488
244 122 61 184 92 46 23 70 35 106
53 160 80 40 20 10 5 16 8 4
2 1
 
Sequence length = 112
 
The longest sequence is for 77031, it has a sequence length of 351.
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Collatz_conjecture}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Part 1.''' Create a routine to generate the hailstone sequence for a number
 
[[File:Fōrmulæ - Collatz conjecture 01.png]]
 
'''Part 2.''' Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with {27, 82, 41, 124} and ending with {8, 4, 2, 1}
 
[[File:Fōrmulæ - Collatz conjecture 02.png]]
 
[[File:Fōrmulæ - Collatz conjecture 03.png]]
 
[[File:Fōrmulæ - Collatz conjecture 04.png]]
 
[[File:Fōrmulæ - Collatz conjecture 05.png]]
 
'''Part 3.''' Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length
 
[[File:Fōrmulæ - Collatz conjecture 06.png]]
 
[[File:Fōrmulæ - Collatz conjecture 07.png]]
 
The sequence for the number 77,031 is the longest one, with 351 terms
 
[[File:Fōrmulæ - Collatz conjecture 08.png]]
 
[[File:Fōrmulæ - Collatz conjecture 09.png]]
 
'''Part 4.''' (Additional, not a requirement) Show the number less than 100,000 which has the highest value in its hailstone sequence together with that highest value
 
[[File:Fōrmulæ - Collatz conjecture 10.png]]
 
[[File:Fōrmulæ - Collatz conjecture 11.png]]
 
The sequence for the number 77,671 has the highest term: 1,570,824,736
 
[[File:Fōrmulæ - Collatz conjecture 12.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Collatz conjecture 13.png]]
In '''[https://formulae.org/?example=Collatz_conjecture this]''' page you can see the program(s) related to this task and their results.
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">CollatzSequence := function(n)
local v;
v := [ n ];
Line 4,624 ⟶ 4,914:
# [ 77031, 351 ]
CollatzMax(1, 1000000);
# [ 837799, 525 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 4,661 ⟶ 4,951:
}
fmt.Printf("hs(%d): %d elements\n", maxN, maxLen)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,675 ⟶ 4,965:
 
Output is the same as version above.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 4,742 ⟶ 5,032:
}
fmt.Printf("hs(%d): %d elements\n", nMaxLen, computedLen[nMaxLen])
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def hailstone = { long start ->
def sequence = []
while (start != 1) {
Line 4,752 ⟶ 5,042:
}
sequence << start
}</langsyntaxhighlight>
Test Code
<langsyntaxhighlight lang="groovy">def sequence = hailstone(27)
assert sequence.size() == 112
assert sequence[0..3] == [27, 82, 41, 124]
Line 4,760 ⟶ 5,050:
 
def results = (1..100000).collect { [n:it, size:hailstone(it).size()] }.max { it.size }
println results</langsyntaxhighlight>
{{out}}
<pre>[n:77031, size:351]</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (maximumBy)
import Data.Ord (comparing)
 
Line 4,796 ⟶ 5,086:
"The sequence has length: "
<> (show . length . hailstone $ longestChain)
]</langsyntaxhighlight>
{{Out}}
<pre>Collatz sequence for 27:
Line 4,805 ⟶ 5,095:
 
The following is an older version, which some of the language examples on this page are translated from:
<langsyntaxhighlight lang="haskell">import Data.Ord (comparing)
import Data.List (maximumBy, intercalate)
 
Line 4,830 ⟶ 5,120:
maximumBy (comparing fst) $
withResult (length . hailstone) <$> [1 .. 100000]
]</langsyntaxhighlight>
{{out}}
<pre>112
Line 4,841 ⟶ 5,131:
One approach to using '''unfoldr''' and then '''foldr''' might be:
 
<langsyntaxhighlight lang="haskell">import Data.List (unfoldr)
 
 
Line 4,891 ⟶ 5,181:
, "length of this sequence:"
, show maxLen
]</langsyntaxhighlight>
{{Out}}
<pre>Sequence 27 length:
Line 4,906 ⟶ 5,196:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">DIMENSION stones(1000)
 
H27 = hailstone(27)
Line 4,939 ⟶ 5,229:
ENDIF
ENDDO
END</langsyntaxhighlight>
H27=112; first4(1)=27; first4(2)=82; first4(3)=41; first4(4)=124; ...; last4(1)=8; last4(2)=4; last4(3)=2; last4(4)=1;
<br /> number=77031; longest_sequence=351;
Line 4,945 ⟶ 5,235:
=={{header|Icon}} and {{header|Unicon}}==
A simple solution that <i>generates</i> (in the Icon sense) the sequence is:
<langsyntaxhighlight lang="icon">procedure hailstone(n)
while n > 1 do {
suspend n
Line 4,951 ⟶ 5,241:
}
suspend 1
end</langsyntaxhighlight>
and a test program for this solution is:
<langsyntaxhighlight lang="icon">procedure main(args)
n := integer(!args) | 27
every writes(" ",hailstone(n))
end</langsyntaxhighlight>
but this solution is computationally expensive when run repeatedly (task 3).
 
The following solution uses caching to improve performance on task 3 at the expense of space.
<langsyntaxhighlight lang="icon">procedure hailstone(n)
static cache
initial {
Line 4,968 ⟶ 5,258:
/cache[n] := [n] ||| hailstone(if n%2 = 0 then n/2 else 3*n+1)
return cache[n]
end</langsyntaxhighlight>
 
A test program is:
<langsyntaxhighlight lang="icon">procedure main(args)
n := integer(!args) | 27
task2(n)
Line 4,993 ⟶ 5,283:
}
write(maxN," has a sequence of ",maxHS," values")
end</langsyntaxhighlight>
A sample run is:
<pre>
Line 5,014 ⟶ 5,304:
This solution uses a cache to speed up the length calculation for larger numbers.
{{works with|Glulx virtual machine}}
<langsyntaxhighlight lang="inform7">Home is a room.
 
To decide which list of numbers is the hailstone sequence for (N - number):
Line 5,066 ⟶ 5,356:
let best number be N;
say "The number under 100,000 with the longest hailstone sequence is [best number] with [best length] element[s].";
end the story.</langsyntaxhighlight>
 
{{out}}
Line 5,074 ⟶ 5,364:
=={{header|Io}}==
Here is a simple, brute-force approach:
<syntaxhighlight lang="io">
<lang io>
makeItHail := method(n,
stones := list(n)
Line 5,113 ⟶ 5,403:
writeln("For numbers less than or equal to 100,000, ", nn,
" has the longest sequence of ", numOfElems, " elements.")
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,125 ⟶ 5,415:
=={{header|Ioke}}==
{{needs-review|Ioke|Calculates the Hailstone sequence but might not complete everything from task description.}}
<langsyntaxhighlight lang="ioke">collatz = method(n,
n println
unless(n <= 1,
if(n even?, collatz(n / 2), collatz(n * 3 + 1)))
)</langsyntaxhighlight>
 
=={{header|J}}==
'''Solution:'''
<langsyntaxhighlight lang="j">hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="j"> # hailseq 27 NB. sequence length
112
4 _4 {."0 1 hailseq 27 NB. first & last 4 numbers in sequence
Line 5,141 ⟶ 5,431:
8 4 2 1
(>:@(i. >./) , >./) #@hailseq }.i. 1e5 NB. number < 100000 with max seq length & its seq length
77031 351</langsyntaxhighlight>
See also the [[j:Essays/Collatz Conjecture|Collatz Conjecture essay on the J wiki]].
 
=={{header|Java}}==
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
Line 5,241 ⟶ 5,531:
return;
}
}</langsyntaxhighlight>
{{out}}
<pre>Sequence for 27 has 112 elements: [27, 82, 41, 124, 62, 31, 94, 47, 142, 71, 214, 107, 322, 161, 484, 242, 121, 364, 182, 91, 274, 137, 412, 206, 103, 310, 155, 466, 233, 700, 350, 175, 526, 263, 790, 395, 1186, 593, 1780, 890, 445, 1336, 668, 334, 167, 502, 251, 754, 377, 1132, 566, 283, 850, 425, 1276, 638, 319, 958, 479, 1438, 719, 2158, 1079, 3238, 1619, 4858, 2429, 7288, 3644, 1822, 911, 2734, 1367, 4102, 2051, 6154, 3077, 9232, 4616, 2308, 1154, 577, 1732, 866, 433, 1300, 650, 325, 976, 488, 244, 122, 61, 184, 92, 46, 23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1]
Line 5,252 ⟶ 5,542:
===ES5===
====Imperative====
<langsyntaxhighlight lang="javascript">function hailstone (n) {
var seq = [n];
while (n > 1) {
Line 5,274 ⟶ 5,564:
}
}
print("longest sequence: " + max + " numbers for starting point " + n);</langsyntaxhighlight>
{{out}}
<pre>sequence 27 is (27, 82, 41, 124 ... 8, 4, 2, 1). length: 112
Line 5,287 ⟶ 5,577:
(translating one of the Haskell solutions).
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
// Hailstone Sequence
Line 5,306 ⟶ 5,596:
};
 
})();</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">{"length":112,"sequence":[27,82,41,124,62,31,94,47,142,71,214,
107,322,161,484,242,121,364,182,91,274,137,412,206,103,310,155,466,233,700,350,
175,526, 263,790,395,1186,593,1780,890,445,1336,668,334,167,502,251,754,377,
Line 5,316 ⟶ 5,606:
2429,7288,3644,1822,911,2734,1367,4102,2051,6154,3077,9232,4616,2308,1154,577,
1732,866,433,1300,650,325,976,488,244,122,61,184,92,46,23,70,35,106,53,160,80,
40,20,10,5,16,8,4,2,1]}</langsyntaxhighlight>
 
Attempting to fold that recursive function over an array of 100,000 elements,
Line 5,325 ⟶ 5,615:
which reuses previously calculated paths.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
 
function memoizedHailstone() {
Line 5,374 ⟶ 5,664:
return longestBelow(100000);
 
})();</langsyntaxhighlight>
 
{{out}}
 
<langsyntaxhighlight JavaScriptlang="javascript">// Number, length of sequence
{"n":77031, "l":351}</langsyntaxhighlight>
 
For better time (as well as space) we can continue to memoize while falling back to a function which returns the
Line 5,386 ⟶ 5,676:
for integers below one million, or ten million and beyond, without hitting the limits of system resources.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (n) {
 
var dctMemo = {};
Line 5,438 ⟶ 5,728:
return [100000, 1000000, 10000000].map(longestBelow);
 
})();</langsyntaxhighlight>
 
{{out}}
 
<syntaxhighlight lang="javascript">[
<lang JavaScript>[
{"n":77031, "l":351}, // 100,000
{"n":837799, "l":525}, // 1,000,000
{"n":8400511, "l":686} // 10,000,000
]</langsyntaxhighlight>
 
<langsyntaxhighlight JavaScriptlang="javascript">longestBelow(100000000)
-> {"n":63728127, "l":950}</langsyntaxhighlight>
 
===ES6===
<langsyntaxhighlight lang="javascript">(() => {
 
// hailstones :: Int -> [Int]
Line 5,555 ⟶ 5,845:
`The length of that sequence is ${maxLen}.`
]);
})();</langsyntaxhighlight>
{{Out}}
(Run in the Atom editor, through the Script package)
Line 5,577 ⟶ 5,867:
=={{header|jq}}==
{{works with|jq|1.4}}
<langsyntaxhighlight lang="jq"># Generate the hailstone sequence as a stream to save space (and time) when counting
def hailstone:
recurse( if . > 1 then
Line 5,592 ⟶ 5,882:
([0,0];
($i | count(hailstone)) as $l
| if $l > .[1] then [$i, $l] else . end);</langsyntaxhighlight>
'''Examples''':
<langsyntaxhighlight lang="jq">[27|hailstone] as $h
| "[27|hailstone]|length is \($h|length)",
"The first four numbers: \($h[0:4])",
Line 5,600 ⟶ 5,890:
"",
max_hailstone(100000) as $m
| "Maximum length for n|hailstone for n in 1..100000 is \($m[1]) (n == \($m[0]))"</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -M -r -n -f hailstone.jq
[27|hailstone]|length is 112
The first four numbers: [27,82,41,124]
The last four numbers: [8,4,2,1]
 
Maximum length for n|hailstone for n in 1..100000 is 351 (n == 77031)</langsyntaxhighlight>
 
=={{header|Julia}}==
Line 5,613 ⟶ 5,903:
 
===Dynamic solution===
<langsyntaxhighlight lang="julia">function hailstonelength(n::Integer)
len = 1
while n > 1
Line 5,623 ⟶ 5,913:
 
@show hailstonelength(27); nothing
@show findmax([hailstonelength(i) for i in 1:100_000]); nothing</langsyntaxhighlight>
 
{{out}}
Line 5,634 ⟶ 5,924:
====Julia 1.0====
{{works with|Julia|1.0+}}
<langsyntaxhighlight lang="julia">struct HailstoneSeq{T<:Integer}
count::T
end
Line 5,672 ⟶ 5,962:
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)))</langsyntaxhighlight>
 
{{out}}
Line 5,683 ⟶ 5,973:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">struct HailstoneSeq{T<:Integer}
start::T
end
Line 5,722 ⟶ 6,012:
 
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)))</langsyntaxhighlight>
 
{{out}}
Line 5,731 ⟶ 6,021:
 
=={{header|K}}==
<langsyntaxhighlight lang="k"> hail: (1<){:[x!2;1+3*x;_ x%2]}\
seqn: hail 27
 
Line 5,742 ⟶ 6,032:
 
{m,x@s?m:|/s:{#hail x}'x}{x@&x!2}!:1e5
351 77031</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang ="kotlin">import java.util.ArrayDeque
fun hailstone(start: Int) = generateSequence(start) { n ->
when {
n == 1 -> null
n % 2 == 0 -> n / 2
else -> n * 3 + 1
}
}
 
fun main() {
val hail27 = hailstone(27).toList()
println("The hailstone sequence for 27 has ${hail27.size} elements:\n$hail27")
 
val (n, length) = (1..100000).asSequence()
.map { it to hailstone(it).count() }
.maxBy { it.second }
println("The number between 1 and 100000 with the longest hailstone sequence is $n, of length $length")
}
</syntaxhighlight>
 
 
Alternative, doing it manually:
 
<syntaxhighlight lang="kotlin">import java.util.ArrayDeque
 
fun hailstone(n: Int): ArrayDeque<Int> {
Line 5,768 ⟶ 6,081:
println("${longestHail.first} is the number less than 100000 with " +
"the longest sequence, having length ${longestHail.size}.")
}</langsyntaxhighlight>
 
{{out}}
Line 5,775 ⟶ 6,088:
 
=={{header|Lasso}}==
<syntaxhighlight lang="lasso">[
<lang Lasso>[
define_tag("hailstone", -required="n", -type="integer", -copy);
local("sequence") = array(#n);
Line 5,806 ⟶ 6,119:
"<br/>";
"Number with the longest sequence under 100,000: " #longest_index + ", with " + #longest_sequence + " elements.";
]</langsyntaxhighlight>
 
=={{header|Limbo}}==
 
<syntaxhighlight lang="text">implement Hailstone;
 
include "sys.m"; sys: Sys;
Line 5,862 ⟶ 6,175:
return i :: hailstone((big 3 * i) + big 1);
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,870 ⟶ 6,183:
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">on hailstone (n, sequenceList)
len = 1
repeat while n<>1
Line 5,883 ⟶ 6,196:
if listP(sequenceList) then sequenceList.add(n)
return len
end</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="lingo">sequenceList = []
hailstone(27, sequenceList)
put sequenceList
Line 5,900 ⟶ 6,213:
end repeat
put n, maxLen
-- 77031 351</langsyntaxhighlight>
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to hail.next :n
output ifelse equal? 0 modulo :n 2 [:n/2] [3*:n + 1]
end
Line 5,925 ⟶ 6,238:
end
 
max.hail 100000</langsyntaxhighlight>
 
=={{header|Logtalk}}==
<langsyntaxhighlight lang="logtalk">:- object(hailstone).
 
:- public(generate_sequence/2).
Line 6,021 ⟶ 6,334:
).
 
:- end_object.</langsyntaxhighlight>
Testing:
<langsyntaxhighlight lang="logtalk">| ?- hailstone::write_sequence(27).
27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
true
Line 6,033 ⟶ 6,346:
| ?- hailstone::longest_sequence(1, 100000, N, Length).
N = 77031, Length = 351
true</langsyntaxhighlight>
 
=={{header|LOLCODE}}==
There is presently no way to query a <tt>BUKKIT</tt> for the existence of a given key, thus making memoization infeasible. This solution takes advantage of prior knowledge to run in reasonable time.
<langsyntaxhighlight LOLCODElang="lolcode">HAI 1.3
 
HOW IZ I hailin YR stone
Line 6,085 ⟶ 6,398:
VISIBLE "len(hail(" max ")) = " len
 
KTHXBYE</langsyntaxhighlight>
{{out}}
<pre>hail(27) = 27 82 41 124 ... 8 4 2 1, length = 112
Line 6,091 ⟶ 6,404:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function hailstone( n, print_numbers )
local n_iter = 1
 
Line 6,120 ⟶ 6,433:
end
 
print( string.format( "Needed %d iterations for the number %d.\n", max_iter, max_i ) )</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Line 6,126 ⟶ 6,439:
 
Also we use current stack as FIFO to get the last 4 numbers
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module hailstone.Task {
hailstone=lambda (n as long)->{
Line 6,175 ⟶ 6,488:
}
hailstone.Task
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,186 ⟶ 6,499:
=={{header|Maple}}==
Define the procedure:
<syntaxhighlight lang="maple">
<lang Maple>
hailstone := proc( N )
local n := N, HS := Array([n]);
Line 6,199 ⟶ 6,512:
HS;
end proc;
</syntaxhighlight>
</lang>
Run the command and show the appropriate portion of the result;
<syntaxhighlight lang="maple">
<lang Maple>
> r := hailstone(27):
[ 1..112 1-D Array ]
Line 6,209 ⟶ 6,522:
> r(1..4) ... r(-4..);
[27, 82, 41, 124] .. [8, 4, 2, 1]
</syntaxhighlight>
</lang>
Compute the first 100000 sequences:
<syntaxhighlight lang="maple">
<lang Maple>
longest := 0; n := 0;
for i from 1 to 100000 do
Line 6,221 ⟶ 6,534:
od:
printf("The longest Hailstone sequence in the first 100k is n=%d, with %d terms\n",n,longest);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,231 ⟶ 6,544:
 
=== Nested function call formulation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneF[n_] := NestWhileList[If[OddQ[#], 3 # + 1, #/2] &, n, # > 1 &]</langsyntaxhighlight>
 
This is probably the most readable and shortest implementation.
 
=== Fixed-Point formulation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneFP[n_] := Most@FixedPointList[Switch[#, 1, 1, _?OddQ , 3# + 1, _, #/2] &, n]</langsyntaxhighlight>
 
=== Recursive formulation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneR[1] = {1}
HailstoneR[n_?OddQ] := Prepend[HailstoneR[3 n + 1], n]
HailstoneR[n_] := Prepend[HailstoneR[n/2], n] </langsyntaxhighlight>
 
=== Procedural implementation ===
<langsyntaxhighlight Mathematicalang="mathematica">HailstoneP[n_] := Module[{x = {n}, s = n},
While[s > 1, x = {x, s = If[OddQ@s, 3 s + 1, s/2]}]; Flatten@x] </langsyntaxhighlight>
 
=== Validation ===
 
I use this version to do the validation:
<langsyntaxhighlight Mathematicalang="mathematica">Hailstone[n_] :=
NestWhileList[If[Mod[#, 2] == 0, #/2, ( 3*# + 1) ] &, n, # != 1 &];
 
Line 6,263 ⟶ 6,576:
{i, 100000}
]
Print["Longest Hailstone sequence at n = ", longest, "\nwith length = ", comp]; </langsyntaxhighlight>
{{out}}
<pre>
Line 6,274 ⟶ 6,587:
 
==== Sequence 27 ====
<langsyntaxhighlight Mathematicalang="mathematica">With[{seq = HailstoneFP[27]}, { Length[seq], Take[seq, 4], Take[seq, -4]}]</langsyntaxhighlight>
{{out}}
<pre>{112, {27, 82, 41, 124}, {8, 4, 2, 1}}</pre>
 
Alternatively,
<syntaxhighlight lang Mathematica="mathematica">Short[HailstoneFP[27],0.45]</langsyntaxhighlight>
 
{{out}}
Line 6,285 ⟶ 6,598:
 
==== Longest sequence length ====
<langsyntaxhighlight Mathematicalang="mathematica">MaximalBy[Table[{i, Length[HailstoneFP[i]]}, {i, 100000}], Last]</langsyntaxhighlight>
{{out}}
<pre>{{77031, 351}}</pre>
Line 6,291 ⟶ 6,604:
=={{header|MATLAB}} / {{header|Octave}}==
===Hailstone Sequence For N===
<langsyntaxhighlight Matlablang="matlab">function x = hailstone(n)
x = n;
while n > 1
Line 6,301 ⟶ 6,614:
end
x(end + 1) = n; %#ok
end</langsyntaxhighlight>
Show sequence of hailstone(27) and number of elements:
<langsyntaxhighlight Matlablang="matlab">x = hailstone(27);
fprintf('hailstone(27): %d %d %d %d ... %d %d %d %d\nnumber of elements: %d\n', x(1:4), x(end-3:end), numel(x))</langsyntaxhighlight>
{{out}}
<pre>hailstone(27): 27 82 41 124 ... 8 4 2 1
Line 6,311 ⟶ 6,624:
Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length:
====Basic Version (use the above routine)====
<langsyntaxhighlight Matlablang="matlab">N = 1e5;
maxLen = 0;
for k = 1:N
Line 6,319 ⟶ 6,632:
n = k;
end
end</langsyntaxhighlight>
{{out}}
<pre>n = 77031
maxLen = 351</pre>
====Faster Version====
<langsyntaxhighlight lang="matlab">function [n, maxLen] = longestHailstone(N)
maxLen = 0;
for k = 1:N
Line 6,341 ⟶ 6,654:
n = k;
end
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="matlab">>> [n, maxLen] = longestHailstone(1e5)
n = 77031
maxLen = 351</langsyntaxhighlight>
====Much Faster Version With Caching====
<langsyntaxhighlight lang="matlab">function [n, maxLen] = longestHailstone(N)
lenList(N) = 0;
lenList(1) = 1;
Line 6,368 ⟶ 6,681:
n = k;
end
end</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="matlab">>> [n, maxLen] = longestHailstone(1e5)
n = 77031
maxLen = 351</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">collatz(n) := block([L], L: [n], while n > 1 do
(n: if evenp(n) then n/2 else 3*n + 1, L: endcons(n, L)), L)$
 
Line 6,389 ⟶ 6,702:
length(%); /* 112 */
collatz_length(27); /* 112 */
collatz_max(100000); /* [77031, 351] */</langsyntaxhighlight>
 
=={{header|Mercury}}==
The actual calculation (including module ceremony)
providing both a function and a predicate implementation:
<langsyntaxhighlight lang="mercury">:- module hailstone.
 
:- interface.
Line 6,412 ⟶ 6,725:
; hailstone(3 * N + 1, S) ).
 
:- end_module hailstone.</langsyntaxhighlight>
 
The mainline test driver (making use of [http://en.wikipedia.org/wiki/Unification_(computer_science) unification] for more succinct tests):
<langsyntaxhighlight lang="mercury">:- module test_hailstone.
 
:- interface.
Line 6,450 ⟶ 6,763:
; io.write_string("At least one test failed.\n", !IO) ).
 
:- end_module test_hailstone.</langsyntaxhighlight>
 
{{out}} of running this program is:
Line 6,457 ⟶ 6,770:
For those unused to logic programming languages it seems that nothing has been proved in terms of confirming anything, but if you look at the predicate declaration for <code>longest/3</code> …
 
<langsyntaxhighlight lang="mercury">:- pred longest(int::in, int::out, int::out) is det.</langsyntaxhighlight>
 
… you see that the second and third parameters are '''output''' parameters.
Line 6,467 ⟶ 6,780:
Thus we know that the correct sequences and values were generated
without bothering to print them out.
 
=={{header|MiniScript}}==
===Non-cached version===
Calculates sequence without using previous calculated sequences.
 
<syntaxhighlight lang="miniscript">
getSequence = function(n)
results = [n]
while n > 1
if n % 2 then
n = 3 * n + 1
else
n = n / 2
end if
results.push n
end while
return results
end function
 
h = getSequence(27)
print "The hailstone sequence for 27 has 112 elements starting with"
print h[:4]
print "and ending with"
print h[-4:]
 
maxSeqLen = 0
maxSeqVal = 0
for i in range(1,100000)
h = getSequence(i)
if h.len > maxSeqLen then
maxSeqLen = h.len
maxSeqVal = i
end if
end for
print
print "The number < 100,000 which has the longest hailstone sequence is " + maxSeqVal + "."
print "This sequence has " + maxSeqLen + " elements."
</syntaxhighlight>
{{out}}
<pre>The hailstone sequence for 27 has 112 elements starting with
[27, 82, 41, 124]
and ending with
[8, 4, 2, 1]
 
The number < 100,000 which has the longest hailstone sequence is 77031.
This sequence has 351 elements.</pre>
 
===Cached version===
Calculations are stored for used in later calculations.
<syntaxhighlight lang="miniscript">
cache = {}
calc = function(n)
if cache.hasIndex(n) then return
items = [n]
origNum = n
while n > 1 and not cache.hasIndex(n)
if n % 2 then
n = 3 * n + 1
else
n = n /2
end if
items.push n
end while
cache[origNum] = {"len": items.len,"items":items}
end function
 
getLen = function(n)
if not cache.hasIndex(n) then calc n
if n == 1 then return 1
return cache[n].len + getLen(cache[n].items[-1]) - 1
end function
 
getSequence = function(n)
if not cache.hasIndex(n) then calc n
if n == 1 then return [1]
return cache[n].items[:-1] + getSequence(cache[n].items[-1])
end function
 
h = getSequence(27)
print "The hailstone sequence for 27 has " + h.len + " elements starting with"
print h[:4]
print "and ending with"
print h[-4:]
 
longSeq = 0
longSeqVal =0
for i in range(2, 100000)
seq = getLen(i)
if longSeq < seq then
longSeq = seq
longSeqVal = i
end if
end for
print "The number < 100,000 which has the longest hailstone sequence is " + longSeqVal + "."
print "This sequence has " + longSeq + " elements."
</syntaxhighlight>
 
{{out}}Output is the same as the non-cached version above.
<pre>The hailstone sequence for 27 has 112 elements starting with
[27, 82, 41, 124]
and ending with
[8, 4, 2, 1]
 
The number < 100,000 which has the longest hailstone sequence is 77031.
This sequence has 351 elements.</pre>
 
=={{header|ML}}==
==={{header|MLite}}===
<langsyntaxhighlight lang="ocaml">fun hail (x = 1) = [1]
| (x rem 2 = 0) = x :: hail (x div 2)
| x = x :: hail (x * 3 + 1)
Line 6,504 ⟶ 6,922:
print ` ref (biggest, 0);
print " and is of length ";
println ` ref (biggest, 1);</langsyntaxhighlight>
{{out}}
<pre>hailstone sequence for the number 27 has 112 elements starting with [27, 82, 41, 124] and ending with [8, 4, 2, 1].
Line 6,510 ⟶ 6,928:
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE hailst;
 
IMPORT InOut;
Line 6,582 ⟶ 7,000:
FindMax (100000);
InOut.WriteString ("Done."); InOut.WriteLn
END hailst.</langsyntaxhighlight>
Producing:
<pre>jan@Beryllium:~/modula/rosetta$ hailst
Line 6,610 ⟶ 7,028:
 
=={{header|MUMPS}}==
<langsyntaxhighlight MUMPSlang="mumps">hailstone(n) ;
If n=1 Quit n
If n#2 Quit n_" "_$$hailstone(3*n+1)
Quit n_" "_$$hailstone(n\2)
Set x=$$hailstone(27) Write !,$Length(x," ")," terms in ",x,!
112 terms in 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight Nanoquerylang="nanoquery">def hailstone(n)
seq = list()
Line 6,649 ⟶ 7,067:
end
print "\nThe number less than 100,000 with the longest sequence is "
println maxLoc + " with a length of " + max</langsyntaxhighlight>
{{out}}
<pre>hailstone(27)
Line 6,658 ⟶ 7,076:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
Line 6,701 ⟶ 7,119:
hs = hs' 'hn
 
return hs.strip</langsyntaxhighlight>
{{out}}
<pre>
Line 6,711 ⟶ 7,129:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc hailstone(n: int): seq[int] =
result = @[n]
var n = n
Line 6,736 ⟶ 7,154:
m = n
mi = i
echo &"\nFor numbers < 100_000, maximum length {m} was found for Hailstone({mi})."</langsyntaxhighlight>
{{out}}
<pre>Hailstone sequence for number 27 has 112 elements.
Line 6,744 ⟶ 7,162:
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">MODULE hailst;
 
IMPORT Out;
Line 6,823 ⟶ 7,241:
Out.String ("Done.");
Out.Ln
END hailst.</langsyntaxhighlight>
Producing
<pre>
Line 6,851 ⟶ 7,269:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#load "nums.cma";;
open Num;;
 
Line 6,913 ⟶ 7,331:
"1732"; "866"; "433"; "1300"; "650"; "325"; "976"; "488"; "244"; "122";
"61"; "184"; "92"; "46"; "23"; "70"; "35"; "106"; "53"; "160"; "80"; "40";
"20"; "10"; "5"; "16"; "8"; "4"; "2"; "1"] *)</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: hailstone // n -- [n]
| l |
ListBuffer new ->l
Line 6,924 ⟶ 7,342:
 
hailstone(27) dup size println dup left(4) println right(4) println
100000 seq map(#[ dup hailstone size swap Pair new ]) reduce(#maxKey) println</langsyntaxhighlight>
 
{{out}}
Line 6,933 ⟶ 7,351:
[351, 77031]
</pre>
 
=={{header|Onyx (wasm)}}==
<syntaxhighlight lang="C">
use core { * }
 
hailstone :: (n: u32) -> [..]u32 {
seq: [..]u32;
array.push(&seq, n);
while n > 1 {
n = n/2 if n%2 == 0 else (n*3)+1;
array.push(&seq, n);
}
return seq;
}
 
Longest :: struct { num, len : u32; }
 
main :: () {
// -------
// task 1:
// -------
// "Create a routine to generate the hailstone
// sequence for a number."
i := 27;
seq := hailstone(i);
printf("Task 1:\n{}: {}\n\n",
i,
seq
);
// -------
// task 2:
// -------
// "Use the routine to show that the hailstone
// sequence for the number 27 has
// 112 elements starting with
// 27, 82, 41, 124 and ending with 8, 4, 2, 1"
slice_size := 4;
len := seq.length;
slice_first := seq[0..slice_size];
slice_last := seq[seq.length-slice_size..seq.length];
printf("Task 2:\nlength: {}, first: {}, last: {}\n\n",
len,
slice_first,
slice_last
);
// -------
// task 3:
// -------
// "Show the number less than 100,000
// which has the longest hailstone sequence
// together with that sequences length."
l : Longest;
for i in 1..100000 {
seq := hailstone(i);
if l.len < seq.length { l = .{num = i, len = seq.length}; }
}
printf("Task 3:\nLongest Num: {}, Sequence Length: {}\n", l.num, l.len);
}
</syntaxhighlight>
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
sequence = hailstone(27)
say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]"
Line 6,963 ⟶ 7,446:
end
return sequence
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 6,972 ⟶ 7,455:
=={{header|Order}}==
To display the length, and first and last elements, of the hailstone sequence for 27, we could do this:
<langsyntaxhighlight lang="c">#include <order/interpreter.h>
 
#define ORDER_PP_DEF_8hailstone ORDER_PP_FN( \
Line 6,988 ⟶ 7,471:
8(starts with:) 8seq_take(4, 8H) 8comma 8space
8(ends with:) 8seq_drop(8minus(8S, 4), 8H))
) )</langsyntaxhighlight>
{{out}}
<syntaxhighlight lang="text">h(27) - length:112, starts with:(27)(82)(41)(124), ends with:(8)(4)(2)(1)</langsyntaxhighlight>
 
Unfortunately, the C preprocessor not really being designed with large amounts of garbage collection in mind, trying to compute the hailstone sequences up to 100000 is almost guaranteed to run out of memory (and take a very, very long time). If we wanted to try, we could add this to the program, which in most languages would use relatively little memory:
<langsyntaxhighlight lang="c">#define ORDER_PP_DEF_8h_longest ORDER_PP_FN( \
8fn(8M, 8P, \
8if(8is_0(8M), \
Line 7,005 ⟶ 7,488:
8let((8P, 8h_longest(8nat(1,0,0,0,0,0), 8pair(0, 0))),
8pair(8to_lit(8tuple_at_0(8P)), 8to_lit(8tuple_at_1(8P))))
)</langsyntaxhighlight>
 
...or even this "more elegant" version, which will run out of memory very quickly indeed (but in practice seems to work better for smaller ranges):
<langsyntaxhighlight lang="c">ORDER_PP(
8let((8P,
8seq_head(
Line 7,016 ⟶ 7,499:
8pair(8N, 8seq_size(8hailstone(8N)))),
8seq_iota(1, 8nat(1,0,0,0,0,0)))))),
8pair(8to_lit(8tuple_at_0(8P)), 8to_lit(8tuple_at_1(8P)))) )</langsyntaxhighlight>
 
Notice that large numbers (>100) must be entered as digit sequences with <code>8nat</code>. <code>8to_lit</code> converts a digit sequence back to a readable number.
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
fun {HailstoneSeq N}
N > 0 = true %% assert
Line 7,044 ⟶ 7,527:
MaxI#MaxLen = {List.foldL Pairs MaxBy2nd 0#0}
{System.showInfo
"Maximum length "#MaxLen#" was found for hailstone("#MaxI#")"}</langsyntaxhighlight>
{{out}}
<pre>
Line 7,053 ⟶ 7,536:
 
===Version #1.===
<langsyntaxhighlight lang="parigp">show(n)={
my(t=1);
while(n>1,
Line 7,083 ⟶ 7,566:
 
show(27)
r=0;for(n=1,1e5,t=len(n);if(t>r,r=t;ra=n));print(ra"\t"r)</langsyntaxhighlight>
{{out}}
<pre>27,82,41,124,62,31,94,47,142,71,214,107,322,161,484,242,121,364,182,91,274,137,4
Line 7,101 ⟶ 7,584:
[http://oeis.org/A070165 A070165]
 
<langsyntaxhighlight lang="parigp">
\\ Get vector with Collatz sequence for the specified starting number.
\\ Limit vector to the lim length, or less, if 1 (one) term is reached (when lim=0).
Line 7,124 ⟶ 7,607:
Collatzmax(1,100000);
}
</syntaxhighlight>
</lang>
 
{{Output}}
Line 7,140 ⟶ 7,623:
See [[Hailstone_sequence#Delphi | Delphi]]
or try this transformed Delphi version without generics.Use of a static array.
<langsyntaxhighlight lang="pascal">program ShowHailstoneSequence;
{$IFDEF FPC}
{$MODE delphi} //or objfpc
Line 7,248 ⟶ 7,731:
limit := limit*10;
until Limit > maxN;
end.</langsyntaxhighlight>
{{out}}
<pre>sequence of 27 has 112 elements
Line 7,269 ⟶ 7,752:
=={{header|Perl}}==
=== Straightforward ===
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
 
use warnings;
Line 7,305 ⟶ 7,788:
 
return @sequence;
}</langsyntaxhighlight>
 
{{out}}
Line 7,316 ⟶ 7,799:
=== Compact ===
A more compact version:
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict;
 
Line 7,330 ⟶ 7,813:
@h = ();
for (1 .. 99_999) { @h = ($_, $h[2]) if ($h[2] = hailstone($_)) > $h[1] }
printf "%d: (%d)\n", @h;</langsyntaxhighlight>
 
 
Line 7,341 ⟶ 7,824:
=={{header|Phix}}==
Copy of [[Hailstone_sequence#Euphoria|Euphoria]]
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function hailstone(atom n)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
sequence s = {n}
<span style="color: #008080;">function</span> <span style="color: #000000;">hailstone</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
while n!=1 do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}</span>
if remainder(n,2)=0 then
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
n /= 2
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">n</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
n = 3*n+1
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
s &= n
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #000000;">s</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">n</span>
return s
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function hailstone_count(atom n)
integer count = 1
<span style="color: #008080;">function</span> <span style="color: #000000;">hailstone_count</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
while n!=1 do
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
if remainder(n,2)=0 then
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
n /= 2
<span style="color: #008080;">if</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">n</span> <span style="color: #0000FF;">/=</span> <span style="color: #000000;">2</span>
n = 3*n+1
<span style="color: #008080;">else</span>
end if
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
count += 1
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
return count
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">count</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
sequence s = hailstone(27)
integer ls = length(s)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">hailstone</span><span style="color: #0000FF;">(</span><span style="color: #000000;">27</span><span style="color: #0000FF;">)</span>
s[5..-5] = {".."}
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"hailstone(27) = %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">shorten</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"numbers"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)})</span>
puts(1,"hailstone(27) = ")
? s
<span style="color: #004080;">integer</span> <span style="color: #000000;">hmax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">imax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span>
printf(1,"length = %d\n\n",ls)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1e5</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
 
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">hailstone_count</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
integer hmax = 1, imax = 1,count
<span style="color: #008080;">if</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">></span><span style="color: #000000;">hmax</span> <span style="color: #008080;">then</span>
for i=2 to 1e5-1 do
<span style="color: #000000;">hmax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">count</span>
count = hailstone_count(i)
<span style="color: #000000;">imax</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</span>
if count>hmax then
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
hmax = count
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
imax = i
end if
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The longest hailstone sequence under 100,000 is %d with %d elements.\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">imax</span><span style="color: #0000FF;">,</span><span style="color: #000000;">hmax</span><span style="color: #0000FF;">})</span>
end for
<!--</syntaxhighlight>-->
 
printf(1,"The longest hailstone sequence under 100,000 is %d with %d elements.\n",{imax,hmax})</lang>
{{out}}
<pre>
hailstone(27) = {27,82,41,124,"...",8,4,2,1," (112 numbers)"}
The longest hailstone sequence under 100,000 is 77031 with 351 elements.
length = 112
 
The longest hailstone sequence under 100,000 is 77031 with 351 elements.
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function hailstone($n,$seq=array()){
$sequence = $seq;
$sequence[] = $n;
Line 7,418 ⟶ 7,898:
foreach($maxResult as $key => $val){
echo 'Number < 100000 with longest Hailstone seq.: ' . $key . ' with length of ' . $val;
}</langsyntaxhighlight>
<pre>
112 Elements.
Line 7,424 ⟶ 7,904:
Number < 100000 with longest Hailstone seq.: 77031 with length of 351
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">import util.
 
go =>
println("H27:"),
H27 = hailstoneseq(27),
H27Len = H27.len,
println(len=H27.len),
println(take(H27,4)++['...']++drop(H27,H27Len-4)),
nl,
 
println("Longest sequence < 100_000:"),
longest_seq(99_999),
 
nl.
 
% The Hailstone value of a number
hailstone(N) = N // 2, N mod 2 == 0 => true.
hailstone(N) = 3*N+1, N mod 2 == 1 => true.
 
% Sequence for a number
hailstoneseq(N) = Seq =>
Seq := [N],
while (N > 1)
N := hailstone(N),
Seq := Seq ++ [N]
end.
 
%
% Use a map to cache the lengths.
% Here we don't care about the actual sequence.
%
longest_seq(Limit) =>
Lens = new_map(), % caching the lengths
MaxLen = 0,
MaxN = 1,
 
foreach(N in 1..Limit-1)
M = N,
CLen = 1,
while (M > 1)
if Lens.has_key(M) then
CLen := CLen + Lens.get(M) - 1,
M := 1
else
M := hailstone(M), % call the
CLen := CLen + 1
end
end,
Lens.put(N, CLen),
if CLen > MaxLen then
MaxLen := CLen,
MaxN := N
end
end,
println([maxLen=MaxLen, maxN=MaxN]),
nl.</syntaxhighlight>
 
{{out}}
<pre>H27:
len = 112
[27,82,41,124,...,8,4,2,1]
 
Longest sequence < 100_000:
[maxLen = 351,maxN = 77031]</pre>
 
===Mode-directed tabling===
If we just want to get the length of the longest sequence - and are not forced to use the same Hailstone function as for the H27 task - then this version using model-directed tabling is faster than longest_seq/1: 0.055s vs 0.127s. (Original idea by Neng-Fa Zhou.)
<syntaxhighlight lang="picat">go2 =>
time(max_chain(MaxN,MaxLen)),
printf("MaxN=%w,MaxLen=%w%n",MaxN,MaxLen).
 
table (-,max)
max_chain(N,Len) =>
between(2,99_999,N),
gen(N,Len).
 
table (+,-)
gen(1,Len) => Len=1.
gen(N,Len), N mod 2 == 0 =>
gen(N div 2,Len1),
Len=Len1+1.
gen(N,Len) =>
gen(3*N+1,Len1),
Len=Len1+1.
</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de hailstone (N)
(make
(until (= 1 (link N))
Line 7,438 ⟶ 8,005:
 
(let N (maxi '((N) (length (hailstone N))) (range 1 100000))
(println N (length (hailstone N))) )</langsyntaxhighlight>
{{out}}
<pre>27 112 (27 82 41 124) - (8 4 2 1)
Line 7,444 ⟶ 8,011:
 
=={{header|Pike}}==
<langsyntaxhighlight Pikelang="pike">#!/usr/bin/env pike
 
int next(int n)
Line 7,482 ⟶ 8,049:
}
write("longest sequence starting at %d has %d elements\n", longest->start, longest->length);
}</langsyntaxhighlight>
 
{{out}}
Line 7,491 ⟶ 8,058:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">test: proc options (main);
declare (longest, n) fixed (15);
declare flag bit (1);
Line 7,528 ⟶ 8,095:
end hailstones;
 
end test;</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 7,649 ⟶ 8,216:
 
==={{header|PL/I-80}}===
<langsyntaxhighlight PLlang="pl/Ii">hailstone_demo: proc options (main);
%replace
true by '1'b,
Line 7,714 ⟶ 8,281:
 
end hailstone_demo;
</syntaxhighlight>
</lang>
{{out}}
<pre>Display hailstone sequence for what number? 27
Line 7,740 ⟶ 8,307:
=={{header|plainTeX}}==
The following code works with any TeX engine.
<langsyntaxhighlight lang="tex">\newif\ifprint
\newcount\itercount
\newcount\currentnum
Line 7,776 ⟶ 8,343:
\repeat
Seed max = \seed, length = \lenmax
\bye</langsyntaxhighlight>
 
pdf or dvi output:
Line 7,790 ⟶ 8,357:
 
=={{header|Pointless}}==
<langsyntaxhighlight lang="pointless">output =
println(format(fmt,
[seqLength, initSeq, tailSeq] ++ toList(longestPair)
Line 7,825 ⟶ 8,392:
step(n) =
if n % 2 == 0 then round(n / 2) else n * 3 + 1</langsyntaxhighlight>
 
{{out}}
Line 7,835 ⟶ 8,402:
=={{header|PowerShell}}==
{{works with|PowerShell|3.0+}}
<syntaxhighlight lang="powershell">
<lang Powershell>
 
function Get-HailStone {
Line 7,856 ⟶ 8,423:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 7,879 ⟶ 8,446:
=={{header|Prolog}}==
1. Create a routine to generate the hailstone sequence for a number.
<langsyntaxhighlight lang="prolog">hailstone(1,[1]) :- !.
hailstone(N,[N|S]) :- 0 is N mod 2, N1 is N / 2, hailstone(N1,S).
hailstone(N,[N|S]) :- 1 is N mod 2, N1 is (3 * N) + 1, hailstone(N1, S).</langsyntaxhighlight>
 
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1.
 
The following query performs the test.
<langsyntaxhighlight lang="prolog">hailstone(27,X),
length(X,112),
append([27, 82, 41, 124], _, X),
append(_, [8, 4, 2, 1], X).</langsyntaxhighlight>
 
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequences length.
<langsyntaxhighlight lang="prolog">longestHailstoneSequence(M, Seq, Len) :- longesthailstone(M, 1, 1, Seq, Len).
longesthailstone(1, Cn, Cl, Mn, Ml):- Mn = Cn,
Ml = Cl.
Line 7,901 ⟶ 8,468:
longesthailstone(N1, N, L, Mn, Ml).
longesthailstone(N, Cn, Cl, Mn, Ml) :- N1 is N-1,
longesthailstone(N1, Cn, Cl, Mn, Ml).</langsyntaxhighlight>
run this query.
<langsyntaxhighlight lang="prolog">longestHailstoneSequence(100000, Seq, Len).</langsyntaxhighlight>
to get the following result
<pre>
Line 7,914 ⟶ 8,481:
Works with SWI-Prolog and module '''chr''' written by '''Tom Schrijvers''' and '''Jan Wielemaker''' <br>
 
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(chr)).
:- chr_option(debug, off).
:- chr_option(optimize, full).
Line 7,930 ⟶ 8,497:
% Hailstone loop
hailstone(1) ==> true.
hailstone(N) ==> N \= 1 | collatz(N, H), hailstone(H).</langsyntaxhighlight>
 
Code for task one :
<langsyntaxhighlight Prologlang="prolog">task1 :-
hailstone(27),
findall(X, find_chr_constraint(hailstone(X)), L),
clean,
% check the requirements
( (length(L, 112), append([27, 82, 41, 124 | _], [8,4,2,1], L)) -> writeln(ok); writeln(ko)).</langsyntaxhighlight>
{{out}}
<pre> ?- task1.
Line 7,944 ⟶ 8,511:
true.</pre>
Code for task two :
<langsyntaxhighlight Prologlang="prolog">longest_sequence :-
seq(2, 100000, 1-[1], Len-V),
format('For ~w sequence has ~w len ! ~n', [V, Len]).
Line 7,965 ⟶ 8,532:
findall(hailstone(X), find_chr_constraint(hailstone(X)), L),
length(L, Len),
clean.</langsyntaxhighlight>
{{out}}
<pre> ?- longest_sequence.
Line 7,973 ⟶ 8,540:
 
=={{header|Pure}}==
<langsyntaxhighlight lang="pure">// 1. Create a routine to generate the hailstone sequence for a number.
type odd x::int = x mod 2;
type even x::int = ~odd x;
Line 8,001 ⟶ 8,568:
(foldr (\ (a,b) (c,d) -> if (b > d) then (a,b) else (c,d))
(0,0)
(map (\ x -> (x, # hailstone x)) (1..100000)));</langsyntaxhighlight>
{{out}}
<pre>
Line 8,010 ⟶ 8,577:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">def hailstone(n):
seq = [n]
while n > 1:
n = 3 * n + 1 if n & 1 else n // 2
seq.append(n)
return seq
 
 
if __name__ == '__main__':
h = hailstone(27)
assert (len(h)==112 and h[:4]==[27, 82, 41, 124] and h[-4:]==[8, 4, 2, 1]112
and h[:4] == [27, 82, 41, 124]
print("Maximum length %i was found for hailstone(%i) for numbers <100,000" %
and h[-4:] == [8, 4, 2, 1])
max((len(hailstone(i)), i) for i in range(1,100000)))</lang>
max_length, n = max((len(hailstone(i)), i) for i in range(1, 100_000))
print(f"Maximum length {max_length} was found for hailstone({n}) "
f"for numbers <100,000")</syntaxhighlight>
 
{{out}}
<pre>Maximum length 351 was found for hailstone(77031) for numbers <100,000</pre>
 
===Using a generator===
<syntaxhighlight lang="python">from itertools import islice
 
 
def hailstone(n):
yield n
while n > 1:
n = 3 * n + 1 if n & 1 else n // 2
yield n
 
 
if __name__ == '__main__':
h = hailstone(27)
assert list(islice(h, 4)) == [27, 82, 41, 124]
for _ in range(112 - 4 * 2):
next(h)
assert list(islice(h, 4)) == [8, 4, 2, 1]
max_length, n = max((sum(1 for _ in hailstone(i)), i)
for i in range(1, 100_000))
print(f"Maximum length {max_length} was found for hailstone({n}) "
f"for numbers <100,000")</syntaxhighlight>
 
{{out}}
<pre>Maximum length 351 was found for hailstone(77031) for numbers <100,000</pre>
 
 
===Composition of pure functions===
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">'''Hailstone sequences'''
 
from itertools import (islice, takewhile)
Line 8,145 ⟶ 8,742:
 
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>The hailstone sequence for 27 has 112 elements,
Line 8,155 ⟶ 8,752:
 
=={{header|Quackery}}==
<langsyntaxhighlight Quackerylang="quackery">[ 1 & ] is odd ( n --> b )
[ []
Line 8,189 ⟶ 8,786:
longest take echo
say " has the longest sequence of any number less than 100000."
cr say "It is " length take echo say " elements long." cr</langsyntaxhighlight>
 
'''Output:'''
<langsyntaxhighlight Quackerylang="quackery">The hailstone sequence for 27 has 112 elements.
It starts with 27 82 41 124 and ends with 8 4 2 1.
 
77031 has the longest sequence of any number less than 100000.
It is 351 elements long.
</syntaxhighlight>
</lang>
 
=={{header|R}}==
===Iterative solution===
<langsyntaxhighlight lang="rsplus">### PART 1:
makeHailstone <- function(n){
hseq <- n
Line 8,234 ⟶ 8,831:
cat("Between ", lower.bound, " and ", upper.bound, ", the input of ",
max.index, " gives the longest hailstone sequence, which has length ",
max.length, ". \n", sep="")</langsyntaxhighlight>
 
{{out}}
Line 8,254 ⟶ 8,851:
===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:
<langsyntaxhighlight lang="rsplus">###Task 1:
collatz <- function(n)
{
Line 8,283 ⟶ 8,880:
cat("The longest sequence before the 100000th is found at n =", longest, "and it has length", seqLenghts[longest], "\n")
#Equivalently, line 1 could have been: seqLenghts <- sapply(Vectorize(collatz)(1:99999), length).
#Another good option would be seqLenghts <- lengths(Vectorize(collatz)(1:99999)).</langsyntaxhighlight>
{{out}}
<pre>The first four elements are: 27 82 41 124 and the last four are: 8 4 2 1
Line 8,289 ⟶ 8,886:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 8,310 ⟶ 8,907:
(printf "for x<=~s, ~s has the longest sequence with ~s items\n"
N (car longest) (cdr longest))
</syntaxhighlight>
</lang>
 
{{out}}
Line 8,321 ⟶ 8,918:
(formerly Perl 6)
 
<syntaxhighlight lang="raku" perl6line>sub hailstone($n) { $n, { $_ %% 2 ?? $_ div 2 !! $_ * 3 + 1 } ... 1 }
 
my @h = hailstone(27);
Line 8,328 ⟶ 8,925:
 
my $m = max ( (1..99_999).race.map: { +hailstone($_) => $_ } );
say "Max length {$m.key} was found for hailstone({$m.value}) for numbers < 100_000";</langsyntaxhighlight>
 
{{out}}
Line 8,338 ⟶ 8,935:
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">
hail: func [
"Returns the hailstone sequence for n"
Line 8,369 ⟶ 8,966:
"the number less than 100000 with the longest hail sequence is"
maxN "with length" maxLen
]</langsyntaxhighlight>
 
{{out}}
<pre>the hail sequence of 27 has length 112 and has the form 27 82 41 ... 4 2 1
the number less than 100000 with the longest hail sequence is 77031 with length 351</pre>
 
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <ShowHailstone 27>
<ShowLongest 100000>;
}
 
Hailstone {
1 = 1;
s.N, <Mod s.N 2>: {
0 = s.N <Hailstone <Div s.N 2>>;
1 = s.N <Hailstone <+ 1 <* 3 s.N>>>;
};
};
 
ShowHailstone {
s.N, <Hailstone s.N>: e.Seq,
<Lenw e.Seq>: s.Len s.1 s.2 s.3 s.4 e.X s.D4 s.D3 s.D2 s.D1
= <Prout 'The hailstone sequence for the number '
<Symb s.N> ' has ' <Symb s.Len> ' elements,\n'
'starting with ' s.1 s.2 s.3 s.4
'and ending with ' s.D4 s.D3 s.D2 <Symb s.D1>'.'>;
}
 
FindLongest {
s.Max = <FindLongest s.Max 1 1 1>;
s.Max s.Max s.Long s.Len = s.Long s.Len;
s.Max s.Cur s.Long s.Len,
<Hailstone s.Cur>: e.CurSeq,
<Lenw e.CurSeq>: s.CurLen e.X,
<+ s.Cur 1>: s.Next,
<Compare s.CurLen s.Len>: {
'+' = <FindLongest s.Max s.Next s.Cur s.CurLen>;
s.X = <FindLongest s.Max s.Next s.Long s.Len>;
};
};
 
ShowLongest {
s.Max, <FindLongest s.Max>: s.Long s.Len
= <Prout 'The number < ' <Symb s.Max> ' which has the longest'
' hailstone sequence is ' <Symb s.Long> '.\n'
'The length of its Hailstone sequence is '
<Symb s.Len> '.'>;
};</syntaxhighlight>
{{out}}
<pre>The hailstone sequence for the number 27 has 112 elements,
starting with 27 82 41 124 and ending with 8 4 2 1.
The number < 100000 which has the longest hailstone sequence is 77031.
The length of its Hailstone sequence is 351.</pre>
 
=={{header|REXX}}==
===non-optimized===
<langsyntaxhighlight lang="rexx">/*REXX program tests a number and also a range for hailstone (Collatz) sequences. */
numeric digits 20 /*be able to handle gihugeic numbers. */
parse arg x y . /*get optional arguments from the C.L. */
Line 8,401 ⟶ 9,047:
s= s n /* [↑] % is REXX integer division. */
end /*#hs*/ /* [↑] append N to the sequence list*/
return s /*return the S string to the invoker.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 8,417 ⟶ 9,063:
::::* &nbsp; previously calculated Collatz sequences (memoization)
::::* &nbsp; a faster method of determining if an integer is even
<langsyntaxhighlight 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". */
numeric digits 20; @.= 0 /*handle big numbers; initialize array.*/
Line 8,452 ⟶ 9,098:
if _>hm then iterate /*Is number out of range? Ignore it.*/
@._= r /*assign subsequence number to array. */
end /*while*/; return s</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre>
Line 8,471 ⟶ 9,117:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
size = 27
aList = []
Line 8,492 ⟶ 9,138:
see "" + aList[i] + " "
next
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
HP-28 emulator's timedog preventing from longlasting code execution, the third item of the task is achieved by calculating the 1-100,000 sequence in increments of 5,000 numbers, with a derivative of the generator that only provides the length of the sequence to increase execution speed.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! Code
! Comments
|-
|
DUP 1 →LIST SWAP
'''WHILE''' DUP 1 ≠ '''REPEAT'''
'''IF''' DUP 2 MOD '''THEN''' 3 * 1 + '''ELSE''' 2 / '''END'''
SWAP OVER + SWAP
'''END''' DROP
≫ 'SYRAQ' STO
1 SWAP '''WHILE''' DUP 1 ≠ '''REPEAT'''
'''IF''' DUP 2 MOD '''THEN''' 3 * 1 + '''ELSE''' 2 / '''END'''
SWAP 1 + SWAP
'''END''' DROP
≫ 'SYRAF' STO
≪ SyMax SYRAF SWAP
DUP 5000 + DUP 4 ROLLD '''FOR''' n
'''IF''' DUP n SYRAF <
'''THEN'''
DROP n SYRAF n 'SyMax' STO
'''END NEXT''' DROP ≫
'SYR5K' STO
|
''( n -- { sequence } )''
initialize sequence with n
Calculate next element
Store it into sequence
Forget n
''( n -- sequence_length )''
Initialize counter
Calculate next element
Increment counter
Forget n
''( n -- n+10000 )''
Initialize loop
If sequence length greater than previous ones...
... memorize n
|}
The following instructions deliver what is required:
27 SYRAQ SIZE
1 SYR5K … SYR5K [20 times] DROP SyMax RCL
{{out}}
<pre>
2: 127
1: 77031
</pre>
=={{header|Ruby}}==
This program uses new methods (Integer#even? and Enumerable#max_by) from Ruby 1.8.7.
{{works with|Ruby|1.8.7}}
<langsyntaxhighlight lang="ruby">def hailstone n
seq = [n]
until n == 1
Line 8,513 ⟶ 9,221:
n = (1 ... 100_000).max_by{|n| hailstone(n).length}
puts "#{n} has a hailstone sequence length of #{hailstone(n).length}"
puts "the largest number in that sequence is #{hailstone(n).max}"</langsyntaxhighlight>
{{out}}
<pre>
Line 8,527 ⟶ 9,235:
This avoids recomputing the end of the sequence.
{{works with|Ruby|1.8.7}}
<langsyntaxhighlight lang="ruby">module Hailstone
ListNode = Struct.new(:value, :size, :succ) do
def each
Line 8,564 ⟶ 9,272:
n = (1 ... 100_000).max_by{|n| Hailstone.sequence(n).size}
puts "#{n} has a hailstone sequence length of #{Hailstone.sequence(n).size}"
puts "the largest number in that sequence is #{Hailstone.sequence(n).max}"</langsyntaxhighlight>
output is the same as the above.
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn hailstone(start : u32) -> Vec<u32> {
let mut res = Vec::new();
let mut next = start;
Line 8,607 ⟶ 9,315:
}
println!("Longest sequence is {} element long for seed {}", max_len, max_seed);
}</langsyntaxhighlight>
{{out}}
<pre>For 27 number of elements is 112
Line 8,614 ⟶ 9,322:
 
=={{header|S-lang}}==
<langsyntaxhighlight Slang="s-lang">% lst=1, return list of elements; lst=0 just return length
define hailstone(n, lst)
{
Line 8,658 ⟶ 9,366:
}
}
() = printf("\n");</langsyntaxhighlight>
{{out}}
<pre>Hailstone(27) has 112 elements starting with:
Line 8,667 ⟶ 9,375:
 
=={{header|SAS}}==
<syntaxhighlight lang="sas">
<lang SAS>
* Create a routine to generate the hailstone sequence for one number;
%macro gen_seq(n);
Line 8,722 ⟶ 9,430:
%mend;
%longest_hailstone(1,99999);
</syntaxhighlight>
</lang>
 
{{out}}
Line 8,739 ⟶ 9,447:
 
=={{header|S-BASIC}}==
<langsyntaxhighlight lang="s-basic">comment
Compute and display "hailstone" (i.e., Collatz) sequence
for a given number and find the longest sequence in the
Line 8,801 ⟶ 9,509:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>Display hailstone sequence for what number? 27
Line 8,825 ⟶ 9,533:
{{libheader|Scala}}
{{works with|Scala|2.10.2}}
<langsyntaxhighlight Scalalang="scala">object HailstoneSequence extends App {
def hailstone(n: Int): Stream[Int] =
n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1))
Line 8,839 ⟶ 9,547:
val (n, len) = (1 until 100000).map(n => (n, hailstone(n).length)).maxBy(_._2)
println(s"Longest hailstone sequence length= $len occurring with number $n.")
}</langsyntaxhighlight>
{{Out}}
<pre>Use the routine to show that the hailstone sequence for the number: 27.
Line 8,849 ⟶ 9,557:
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">(define (collatz n)
(if (= n 1) '(1)
(cons n (collatz (if (even? n) (/ n 2) (+ 1 (* 3 n)))))))
Line 8,876 ⟶ 9,584:
 
(collatz-max 1 100000)
; (77031 351)</langsyntaxhighlight>
 
=={{header|Scilab}}==
{{trans|MATLAB}}
<syntaxhighlight lang="text">function x=hailstone(n)
// iterative definition
// usage: global verbose; verbose=%T; hailstone(27)
Line 8,912 ⟶ 9,620:
M(k)=hailstone(k);
end;
[maxLength,n]=max(M)</langsyntaxhighlight>
{{out}}
<pre>27 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
Line 8,920 ⟶ 9,628:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array integer: hailstone (in var integer: n) is func
Line 8,977 ⟶ 9,685:
writeln(" length=" <& length(h27));
writeln("Maximum length " <& maxLength <& " at number=" <& numberOfMaxLength);
end func;</langsyntaxhighlight>
 
{{out}}
Line 8,985 ⟶ 9,693:
Maximum length 351 at number=77031
</pre>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program hailstone_sequence;
hail27 := hailstone(27);
print("The hailstone sequence for the number 27 has", #hail27, "elements,");
print("starting with", hail27(..4), "and ending with", hail27(#hail27-3..));
 
sizes := [#hailstone(n) : n in [1..99999]];
maxsize := max/sizes;
maxelem := [n : n in [1..#sizes] | sizes(n) = maxsize](1);
 
print("The number < 100,000 with the longest hailstone sequence is",maxelem);
print("The length of its sequence is",sizes(maxelem));
 
proc hailstone(n);
seq := [];
loop doing seq with:= n; while n/=1 do
if even n then
n div:= 2;
else
n := 3*n + 1;
end if;
end loop;
return seq;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>The hailstone sequence for the number 27 has 112 elements,
starting with [27 82 41 124] and ending with [8 4 2 1]
The number < 100,000 with the longest hailstone sequence is 77031
The length of its sequence is 351</pre>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func hailstone (n) {
var sequence = [n]
while (n > 1) {
Line 9,010 ⟶ 9,749:
}
 
printf("%d: (%d)\n", h...)</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Object subclass: Sequences [
Sequences class >> hailstone: n [
|seq|
Line 9,036 ⟶ 9,775:
ifFalse: [ ^ Sequences hailstoneCount: ( (3*n) + 1) num: (m + 1) ].
]
].</langsyntaxhighlight>
 
<langsyntaxhighlight lang="smalltalk">|r|
r := Sequences hailstone: 27. "hailstone 'from' 27"
(r size) displayNl. "its length"
Line 9,057 ⟶ 9,796:
 
('Sequence generator %1, sequence length %2' % { (longest at: 1) . (longest at: 2) })
displayNl.</langsyntaxhighlight>
 
=={{header|SNUSP}}==
Line 9,072 ⟶ 9,811:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">
<lang Swift>
func hailstone(var n:Int) -> [Int] {
 
Line 9,106 ⟶ 9,845:
}
 
println("Longest sequence for numbers under 100,000 is with \(longest.n). Which has \(longest.len) items.")</langsyntaxhighlight>
{{out}}
<pre>
Line 9,115 ⟶ 9,854:
=={{header|Tcl}}==
The core looping structure is an example of an [[Loops/N plus one half|n-plus-one-half loop]], except the loop is officially infinite here.
<langsyntaxhighlight lang="tcl">proc hailstone n {
while 1 {
lappend seq $n
Line 9,133 ⟶ 9,872:
if {$l>$maxlen} {set maxlen $l;set max $i}
}
puts "max is $max, with length $maxlen"</langsyntaxhighlight>
 
{{out}}
Line 9,145 ⟶ 9,884:
=={{header|TI-83 BASIC}}==
===Task 1===
<langsyntaxhighlight lang="ti83b">prompt N
N→M: 0→X: 1→L
While L=1
Line 9,159 ⟶ 9,898:
End
End
{N,X}</langsyntaxhighlight>
{{out}}
<pre> 10
Line 9,171 ⟶ 9,910:
===Task 2===
As the calculator is quite slow, so the output is for N=200
<langsyntaxhighlight lang="ti83b">prompt N
0→A:0→B
for(I,1,N)
Line 9,191 ⟶ 9,930:
Disp {I,X}
End
{A,B}</langsyntaxhighlight>
{{out}}
<pre>{171,125}</pre>
 
=={{header|Transd}}==
{{trans|Python}}
<syntaxhighlight lang="scheme">#lang transd
 
MainModule: {
hailstone: (λ n Int()
(with seq Vector<Int>([n])
(while (> n 1)
(= n (if (mod n 2) (+ (* 3 n) 1)
else (/ n 2)))
(append seq n)
)
(ret seq)
)
),
 
_start: (λ
(with h (hailstone 27) l 0 n 0 t 0
(lout "Length of (27): " (size h))
(lout "First 4 of (27): " Range(in: h 0 4))
(lout "Last 4 of (27): " Range(in: h -4 -0))
(for i in Range(100000) do
(= t (size (hailstone (to-Int i)))) (if (> t l) (= l t) (= n i))
)
(lout "For n < 100.000 the max. sequence length is " l " for " n)
)
)
}</syntaxhighlight>{{out}}
<pre>
Length of (27): 112
First 4 of (27): [27, 82, 41, 124]
Last 4 of (27): [8, 4, 2, 1]
For n < 100.000 the max. sequence length is 351 for 77031
</pre>
 
=={{header|TXR}}==
<langsyntaxhighlight lang="txr">@(do (defun hailstone (n)
(cons n
(gen (not (eq n 1))
Line 9,221 ⟶ 9,995:
(set max len)
(set maxi i))))
(format t "longest sequence is ~a for n = ~a\n" max maxi)))</langsyntaxhighlight>
 
<pre>$ txr -l hailstone.txr
Line 9,228 ⟶ 10,002:
=={{header|uBasic/4tH}}==
{{Trans|FreeBASIC}}
<syntaxhighlight lang="text">' ------=< MAIN >=------
 
m = 0
Line 9,296 ⟶ 10,070:
Loop
 
Return (b@)</langsyntaxhighlight>
uBasic is an interpreted language. Doing a sequence up to 100,000 would take over an hour, so we did up to 10,000 here.
{{out}}<pre>sequence for number 27
Line 9,322 ⟶ 10,096:
The best way is to use a shell with built-in arrays and arithmetic, such as Bash.
{{works with|Bash}}
<langsyntaxhighlight lang="bash">#!/bin/bash
# seq is the array genereated by hailstone
# index is used for seq
Line 9,358 ⟶ 10,132:
done
 
echo "${max} has a hailstone sequence length of ${maxlen}"</langsyntaxhighlight>
 
{{out}}
Line 9,373 ⟶ 10,147:
 
{{works with|Bourne Shell}}
<langsyntaxhighlight lang="bash"># Outputs a hailstone sequence from $1, with one element per line.
# Clobbers $n.
hailstone() {
Line 9,402 ⟶ 10,176:
i=`expr $i + 1`
done
echo "Hailstone sequence from $max has $maxlen elements."</langsyntaxhighlight>
 
==={{header|C Shell}}===
Line 9,408 ⟶ 10,182:
This script is '''slow''', but it can reach 100000, and a fast computer might run it in less than 15 minutes.
 
<langsyntaxhighlight lang="csh"># Outputs a hailstone sequence from !:1, with one element per line.
# Clobbers $n.
alias hailstone eval \''@ n = \!:1:q \\
Line 9,458 ⟶ 10,232:
@ i += 1
end
echo "Hailstone sequence from $max has $maxlen elements."</langsyntaxhighlight>
 
{{out}}
Line 9,469 ⟶ 10,243:
===Implementation===
<b>hailstone.u</b>
<langsyntaxhighlight lang="ursa">import "math"
 
def hailstone (int n)
Line 9,483 ⟶ 10,257:
append n seq
return seq
end hailstone</langsyntaxhighlight>
 
===Usage===
Line 9,507 ⟶ 10,281:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 9,518 ⟶ 10,292:
<
^T(@ixX take/$4; %nLP~~lrxPX; ^|TL/~& :/'...',' has length '--@h+ %nP+ length) hail 27,
^|TL(~&,:/' has sequence length ') %nP~~ nleq$^&r ^(~&,length+ hail)* nrange/1 100000></langsyntaxhighlight>
The <code>hail</code> function computes the sequence as follows.
* Given a number as an argument, <code>@iNC</code> makes a list containing only that number before passing it to the rest of the function. The <code>i</code> in the expression stands for the identity function, <code>N</code> for the constant null function, and <code>C</code> for the cons operator.
Line 9,541 ⟶ 10,315:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Private Function hailstone(ByVal n As Long) As Collection
Dim s As New Collection
s.Add CStr(n), CStr(n)
Line 9,594 ⟶ 10,368:
Next i
Debug.Print "The longest hailstone sequence under 100,000 is"; imax; "with"; hmax; "elements."
End Sub</langsyntaxhighlight>{{out}}<pre>hailstone(27) = 27, 82, 41, 124, ... 16, 8, 4, 2, 1
length = 112
The longest hailstone sequence under 100,000 is 77031 with 351 elements.</pre>
 
=={{header|VBScript}}==
<syntaxhighlight lang="vb">
<lang vb>
'function arguments: "num" is the number to sequence and "return" is the value to return - "s" for the sequence or
'"e" for the number elements.
Line 9,642 ⟶ 10,416:
WScript.StdOut.WriteLine "Number less than 100k with the longest sequence: "
WScript.StdOut.WriteLine n_longest
</syntaxhighlight>
</lang>
 
{{Out}}
Line 9,656 ⟶ 10,430:
{{trans|PL/I}}
{{works with|Visual Basic|VB6 Standard}}
<langsyntaxhighlight lang="vb">Option Explicit
Dim flag As Boolean ' true to print values
Sub main()
Line 9,712 ⟶ 10,486:
End If
hailstones = p
End Function 'hailstones</langsyntaxhighlight>
{{Out}}
<pre>The sequence for 27 is: 27 82 41 124 ... 8 4 2 1
Line 9,720 ⟶ 10,494:
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2005+}}
<langsyntaxhighlight lang="vbnet">Module HailstoneSequence
Sub Main()
' Checking sequence of 27.
Line 9,761 ⟶ 10,535:
End Function
 
End Module</langsyntaxhighlight>
 
{{out}}
Line 9,768 ⟶ 10,542:
Max elements in sequence for number below 100k: 77031 with 351 elements.
</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">// 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
fn hs(nn int, recycle []int) []int {
mut n := nn
mut s := recycle[..0]
s << n
for n > 1 {
if n&1 == 0 {
n /= 2
} else {
n = 3*n + 1
}
s << n
}
return s
}
fn main() {
mut seq := hs(27, [])
println("hs(27): $seq.len elements: [${seq[0]} ${seq[1]} ${seq[2]} ${seq[3]} ... ${seq[seq.len-4]} ${seq[seq.len-3]} ${seq[seq.len-2]} ${seq[seq.len-1]}]")
mut max_n, mut max_len := 0,0
for n in 1..100000 {
seq = hs(n, seq)
if seq.len > max_len {
max_n = n
max_len = seq.len
}
}
println("hs($max_n): $max_len elements")
}</syntaxhighlight>
{{out}}
<pre>hs(27): 112 elements: [27 82 41 124 ... 8 4 2 1]
hs(77031): 351 elements</pre>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var hailstone = Fn.new { |n|
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
var h = [n]
Line 9,798 ⟶ 10,609:
}
System.print(" Longest = %(longest)")
System.print(" Length = %(longlen)")</langsyntaxhighlight>
 
{{out}}
Line 9,813 ⟶ 10,624:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
int Seq(1000); \more than enough for longest sequence
 
Line 9,842 ⟶ 10,653:
];
IntOut(0, SN); Text(0, "'s Hailstone length = "); IntOut(0, MaxLen);
]</langsyntaxhighlight>
 
{{out}}
Line 9,855 ⟶ 10,666:
===Show The Sequence with n=27===
Output is in hexadecimal but is otherwise correct.
<langsyntaxhighlight lang="z80">;;;;;;;;;;;;;;;;;;; HEADER ;;;;;;;;;;;;;;;;;;;
read "\SrcCPC\winape_macros.asm"
read "\SrcCPC\MemoryMap.asm"
Line 10,001 ⟶ 10,812:
 
HailstoneBuffer:
ds 512,0</langsyntaxhighlight>
 
{{out}}
Line 10,024 ⟶ 10,835:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn collatz(n,z=L()){ z.append(n); if(n==1) return(z);
if(n.isEven) return(self.fcn(n/2,z)); return(self.fcn(n*3+1,z)) }</langsyntaxhighlight>
This uses tail recursion and thus is stack efficient.
{{out}}
Line 10,038 ⟶ 10,849:
</pre>
Rather than write a function that calculates the length, just roll through all 100,000 sequences and save the largest (length,sequence start) pair. Creating all those Collatz lists isn't quick. This works by using a [mutable] list to hold state as the pump does the basic looping.
<langsyntaxhighlight lang="zkl">[2..0d100_000].pump(Void, // loop n from 2 to 100,000
collatz, // generate Collatz sequence(n)
fcn(c,n){ // if new longest sequence, save length/C, return longest
if(c.len()>n[0]) n.clear(c.len(),c[0]); n}.fp1(L(0,0)))</langsyntaxhighlight>
{{out}}
<pre>
Line 10,049 ⟶ 10,860:
=={{header|ZX Spectrum Basic}}==
{{trans|BBC_BASIC}}
<langsyntaxhighlight lang="zxbasic">10 LET n=27: LET s=1
20 GO SUB 1000
30 PRINT '"Sequence length = ";seqlen
Line 10,069 ⟶ 10,880:
1060 LET l=l+1
1070 GO TO 1020
2000 DEF FN m(a,b)=a-INT (a/b)*b</langsyntaxhighlight>
2,093

edits