September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -4,16 +4,16 @@ The Hailstone sequence of numbers can be generated from a starting positive inte
* &nbsp; If &nbsp; n &nbsp; is &nbsp; '''odd''' &nbsp; then the next &nbsp; n &nbsp; of the sequence &nbsp; <big><code> = (3 * n) + 1 </code></big>
The (unproven), &nbsp; [[wp:Collatz conjecture|Collatz conjecture]] &nbsp; is that the hailstone sequence for any starting number always terminates.
The (unproven) [[wp:Collatz conjecture|Collatz conjecture]] is that the hailstone sequence for any starting number always terminates.
The &nbsp; ''hailstone sequence'' &nbsp; is also known as &nbsp; ''hailstone numbers'' &nbsp; (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). &nbsp; The &nbsp; ''hailstone sequence'' &nbsp; is also sometimes known as the &nbsp; ''Collatz sequence''.
The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the ''Collatz sequence''.
;Task:
# &nbsp; Create a routine to generate the hailstone sequence for a number.
# &nbsp; Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with <code>27, 82, 41, 124</code> and ending with <code>8, 4, 2, 1</code>
# &nbsp; Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.<br> &nbsp; (But don't show the actual sequence!)
# Create a routine to generate the hailstone sequence for a number.
# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with <code>27, 82, 41, 124</code> and ending with <code>8, 4, 2, 1</code>
# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.<br> &nbsp; (But don't show the actual sequence!)
;See also:

View file

@ -1,91 +1,23 @@
' version 17-06-2015
' compile with: fbc -s console
Function hailstone_fast(number As ULongInt) As ULongInt
' faster version
' only counts the sequence
Dim As ULongInt count = 1
While number <> 1
If (number And 1) = 1 Then
number += number Shr 1 + 1 ' 3*n+1 and n/2 in one
count += 2
Else
number Shr= 1 ' divide number by 2
count += 1
End If
Wend
Return count
End Function
Sub hailstone_print(number As ULongInt)
' print the number and sequence
Dim As ULongInt count = 1
Print "sequence for number "; number
Print Using "########"; number; 'starting number
While number <> 1
If (number And 1) = 1 Then
number = number * 3 + 1 ' n * 3 + 1
count += 1
Else
number = number \ 2 ' n \ 2
count += 1
End If
Print Using "########"; number;
Wend
Print : Print
Print "sequence length = "; count
Print
Print String(79,"-")
End Sub
Function hailstone(number As ULongInt) As ULongInt
' normal version
' only counts the sequence
Dim As ULongInt count = 1
While number <> 1
If (number And 1) = 1 Then
number = number * 3 + 1 ' n * 3 + 1
count += 1
End If
number = number \ 2 ' divide number by 2
count += 1
Wend
Return count
End Function
' ------=< MAIN >=------
Dim As ULongInt number
Dim As UInteger x, max_x, max_seq
hailstone_print(27)
Print
For x As UInteger = 1 To 100000
number = hailstone(x)
If number > max_seq Then
max_x = x
max_seq = number
End If
Next
Print "The longest sequence is for "; max_x; ", it has a sequence length of "; max_seq
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print : Print "hit any key to end program"
Sleep
End
100 PRINT : PRINT "HAILSTONE SEQUENCE FOR N = 27:"
110 N=27 : SHOW=1
120 GOSUB 1000
130 PRINT X"ELEMENTS"
140 PRINT : PRINT "FINDING N WITH THE LONGEST HAILSTONE SEQUENCE"
150 SHOW=0
160 T0 = TI
170 FOR N=2 TO 100000
180 : GOSUB 1000
190 : IF X>MAX THEN MAX=X : NMAX = N
200 : REM' PRINT N,X,MAX
210 NEXT
230 PRINT "LONGEST HAILSTONE SEQUENCE STARTS WITH "NMAX"."
240 PRINT "IT HAS"MAX"ELEMENTS"
260 END
1000 REM '*** HAILSTONE SEQUENCE SUBROUTINE ***
1010 X = 0 : S = N
1020 IF SHOW THEN PRINT S,
1030 X = X+1
1040 IF S=1 THEN RETURN
1050 IF INT(S/2)=S/2 THEN S = S/2 : GOTO 1020
1060 S = 3*S+1
1070 GOTO 1020

View file

@ -1,52 +1,91 @@
print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
while hailstone < 1 or hailstone <> int(hailstone)
input "Please enter a positive integer: "; hailstone
wend
print ""
print "The following is the 'Hailstone Sequence' for your number..."
print ""
print hailstone
while hailstone <> 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
print hailstone
wend
print ""
input "Hit 'Enter' to continue to part 2...";dummy$
cls
print "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."
print ""
print "No. in Seq.","Hailstone Sequence Number for 27"
print ""
c = 1: hailstone = 27
print c, hailstone
while hailstone <> 1
c = c + 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
print c, hailstone
wend
print ""
input "Hit 'Enter' to continue to part 3...";dummy$
cls
print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!"
print ""
print "Calculating result... Please wait... This could take a little while..."
print ""
print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far"
print ""
for cc = 1 to 99999
hailstone = cc: c = 1
while hailstone <> 1
c = c + 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
wend
if c > max then max = c: largesthailstone = cc
locate 1, 7
print " "
locate 1, 7
print using("###.###", cc / 99999 * 100);"%", cc, c, max
scan
next cc
print ""
print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"."
end
' version 17-06-2015
' compile with: fbc -s console
Function hailstone_fast(number As ULongInt) As ULongInt
' faster version
' only counts the sequence
Dim As ULongInt count = 1
While number <> 1
If (number And 1) = 1 Then
number += number Shr 1 + 1 ' 3*n+1 and n/2 in one
count += 2
Else
number Shr= 1 ' divide number by 2
count += 1
End If
Wend
Return count
End Function
Sub hailstone_print(number As ULongInt)
' print the number and sequence
Dim As ULongInt count = 1
Print "sequence for number "; number
Print Using "########"; number; 'starting number
While number <> 1
If (number And 1) = 1 Then
number = number * 3 + 1 ' n * 3 + 1
count += 1
Else
number = number \ 2 ' n \ 2
count += 1
End If
Print Using "########"; number;
Wend
Print : Print
Print "sequence length = "; count
Print
Print String(79,"-")
End Sub
Function hailstone(number As ULongInt) As ULongInt
' normal version
' only counts the sequence
Dim As ULongInt count = 1
While number <> 1
If (number And 1) = 1 Then
number = number * 3 + 1 ' n * 3 + 1
count += 1
End If
number = number \ 2 ' divide number by 2
count += 1
Wend
Return count
End Function
' ------=< MAIN >=------
Dim As ULongInt number
Dim As UInteger x, max_x, max_seq
hailstone_print(27)
Print
For x As UInteger = 1 To 100000
number = hailstone(x)
If number > max_seq Then
max_x = x
max_seq = number
End If
Next
Print "The longest sequence is for "; max_x; ", it has a sequence length of "; max_seq
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print : Print "hit any key to end program"
Sleep
End

View file

@ -1,37 +1,52 @@
function Hailstone(sys *n)
'=========================
if n and 1
n=n*3+1
else
n=n>>1
end if
end function
function HailstoneSequence(sys n) as sys
'=======================================
count=1
do
Hailstone n
Count++
if n=1 then exit do
end do
return count
end function
'MAIN
'====
maxc=0
maxn=0
e=100000
for n=1 to e
c=HailstoneSequence n
if c>maxc
maxc=c
maxn=n
end if
next
print e ", " maxn ", " maxc
'result 100000, 77031, 351
print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
while hailstone < 1 or hailstone <> int(hailstone)
input "Please enter a positive integer: "; hailstone
wend
print ""
print "The following is the 'Hailstone Sequence' for your number..."
print ""
print hailstone
while hailstone <> 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
print hailstone
wend
print ""
input "Hit 'Enter' to continue to part 2...";dummy$
cls
print "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."
print ""
print "No. in Seq.","Hailstone Sequence Number for 27"
print ""
c = 1: hailstone = 27
print c, hailstone
while hailstone <> 1
c = c + 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
print c, hailstone
wend
print ""
input "Hit 'Enter' to continue to part 3...";dummy$
cls
print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!"
print ""
print "Calculating result... Please wait... This could take a little while..."
print ""
print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far"
print ""
for cc = 1 to 99999
hailstone = cc: c = 1
while hailstone <> 1
c = c + 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
wend
if c > max then max = c: largesthailstone = cc
locate 1, 7
print " "
locate 1, 7
print using("###.###", cc / 99999 * 100);"%", cc, c, max
scan
next cc
print ""
print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"."
end

View file

@ -1,48 +1,37 @@
NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array
function Hailstone(sys *n)
'=========================
if n and 1
n=n*3+1
else
n=n>>1
end if
end function
Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list
Shared Hailstones() ; Get access to the Hailstones-List
ClearList(Hailstones()) ; Remove old data
Repeat
AddElement(Hailstones()) ; Add an element to the list
Hailstones()=n ; Fill current value in the new list element
If n=1
ProcedureReturn ListSize(Hailstones())
ElseIf n%2=0
n/2
Else
n=(3*n)+1
EndIf
ForEver
EndProcedure
function HailstoneSequence(sys n) as sys
'=======================================
count=1
do
Hailstone n
Count++
if n=1 then exit do
end do
return count
end function
If OpenConsole()
Define i, l, maxl, maxi
l=FillHailstones(27)
Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$)
ForEach Hailstones()
If i=6
Print(#CRLF$)
i=0
EndIf
i+1
Print(RSet(Str(Hailstones()),5))
If Hailstones()<>1
Print(", ")
EndIf
Next
'MAIN
'====
i=1
Repeat
l=FillHailstones(i)
If l>maxl
maxl=l
maxi=i
EndIf
i+1
Until i>=100000
Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.")
maxc=0
maxn=0
e=100000
for n=1 to e
c=HailstoneSequence n
if c>maxc
maxc=c
maxn=n
end if
next
Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
EndIf
print e ", " maxn ", " maxc
'result 100000, 77031, 351

View file

@ -1,40 +1,48 @@
print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
NewList Hailstones.i() ; Make a linked list to use as we do not know the numbers of elements needed for an Array
while hailstone < 1 or hailstone <> int(hailstone)
input "Please enter a positive integer: "; hailstone
wend
count = doHailstone(hailstone,"Y")
Procedure.i FillHailstones(n) ; Fills the list & returns the amount of elements in the list
Shared Hailstones() ; Get access to the Hailstones-List
ClearList(Hailstones()) ; Remove old data
Repeat
AddElement(Hailstones()) ; Add an element to the list
Hailstones()=n ; Fill current value in the new list element
If n=1
ProcedureReturn ListSize(Hailstones())
ElseIf n%2=0
n/2
Else
n=(3*n)+1
EndIf
ForEver
EndProcedure
print: print "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."
count = doHailstone(27,"Y")
If OpenConsole()
Define i, l, maxl, maxi
l=FillHailstones(27)
Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$)
ForEach Hailstones()
If i=6
Print(#CRLF$)
i=0
EndIf
i+1
Print(RSet(Str(Hailstones()),5))
If Hailstones()<>1
Print(", ")
EndIf
Next
print: print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!"
print "Calculating result... Please wait... This could take a little while..."
print "Stone Percent Count"
for i = 1 to 99999
count = doHailstone(i,"N")
if count > maxCount then
theBigStone = i
maxCount = count
print using("#####",i);" ";using("###.#", i / 99999 * 100);"% ";using("####",count)
end if
next i
end
i=1
Repeat
l=FillHailstones(i)
If l>maxl
maxl=l
maxi=i
EndIf
i+1
Until i>=100000
Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.")
'---------------------------------------------
' pass number and print (Y/N)
FUNCTION doHailstone(hailstone,prnt$)
if prnt$ = "Y" then
print
print "The following is the 'Hailstone Sequence' for number:";hailstone
end if
while hailstone <> 1
if (hailstone and 1) then hailstone = (hailstone * 3) + 1 else hailstone = hailstone / 2
doHailstone = doHailstone + 1
if prnt$ = "Y" then
print hailstone;chr$(9);
if (doHailstone mod 10) = 0 then print
end if
wend
END FUNCTION
Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
EndIf

View file

@ -1,23 +0,0 @@
seqlen% = FNhailstone(27, TRUE)
PRINT '"Sequence length = "; seqlen%
maxlen% = 0
FOR number% = 2 TO 100000
seqlen% = FNhailstone(number%, FALSE)
IF seqlen% > maxlen% THEN
maxlen% = seqlen%
maxnum% = number%
ENDIF
NEXT
PRINT "The number with the longest hailstone sequence is " ; maxnum%
PRINT "Its sequence length is " ; maxlen%
END
DEF FNhailstone(N%, S%)
LOCAL L%
IF S% THEN PRINT N%;
WHILE N% <> 1
IF N% AND 1 THEN N% = 3 * N% + 1 ELSE N% DIV= 2
IF S% THEN PRINT N%;
L% += 1
ENDWHILE
= L% + 1

View file

@ -0,0 +1,3 @@
>@:N q
>%"d3~@.PNp
d~2~pL~1F{<T_

View file

@ -0,0 +1,4 @@
>@:N q
>%"d3~@.PNq
d~2~qL~1Ff{<BF3_
{NNgA<

View file

@ -0,0 +1,30 @@
27
82
41
124
62
31
94
47
...
2158
1079
3238
1619
4858
2429
7288
3644
1822
...
16
8
4
2
1
112

View file

@ -0,0 +1,5 @@
>@: 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

View file

@ -0,0 +1 @@
77031 351

View file

@ -17,7 +17,7 @@ fun hailstone_seq(x: int): []int =
let x = hailstone_step x
let steps[i] = x
in (capacity, i+1, steps, x)
in (split i steps).0
in #1 (split i steps)
fun hailstone_len(x: int): int =
let i = 1

View file

@ -1,18 +1,26 @@
import Data.List (maximumBy)
import Data.Ord (comparing)
main = do putStrLn $ "Collatz sequence for 27: "
++ ((show.hailstone) 27)
++ "\n"
++ "The number "
++ (show longestChain)
++" has the longest hailstone sequence"
++" for any number less then 100000. "
++"The sequence has length "
++ (show.length.hailstone $ longestChain)
hailstone :: Int -> [Int]
hailstone = takeWhile (/= 1) . iterate collatz
where
collatz n =
if even n
then n `div` 2
else 3 * n + 1
hailstone = takeWhile (/=1) . (iterate collatz)
where collatz n = if even n then n `div` 2 else 3*n+1
longestChain :: Int
longestChain =
fst
(maximumBy (comparing snd) (((,) <*> length . hailstone) <$> [1 .. 100000]))
longestChain = fst $ maximumBy (comparing snd) $
map ((\x -> (x,(length.hailstone) x))) [1..100000]
--TEST -------------------------------------------------------------------------
main =
mapM_
putStrLn
[ "Collatz sequence for 27: "
, (show . hailstone) 27
, "The number " ++ show longestChain
, "has the longest hailstone sequence for any number less then 100000. "
, "The sequence has length: " ++ (show . length . hailstone $ longestChain)
]

View file

@ -1,19 +1,26 @@
import Data.List (maximumBy)
import Data.Ord (comparing)
import Data.List (maximumBy, intercalate)
hailstone :: Int -> [Int]
hailstone 1 = [1]
hailstone n | even n = n : hailstone (n `div` 2)
| otherwise = n : hailstone (n * 3 + 1)
hailstone 1 = [1]
hailstone n
| even n = n : hailstone (n `div` 2)
| otherwise = n : hailstone (n * 3 + 1)
withResult :: (t -> t1) -> t -> (t1, t)
withResult :: (Int -> Int) -> Int -> (Int, Int)
withResult f x = (f x, x)
h27 :: [Int]
h27 = hailstone 27
main :: IO ()
main = do
let h27 = hailstone 27
print $ length h27
let h4 = show $ take 4 h27
let t4 = show $ drop (length h27 - 4) h27
putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4)
print $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000]
main =
mapM_
putStrLn
[ (show . length) h27
, "hailstone 27: " ++
intercalate " ... " (show <$> [take 4 h27, drop (length h27 - 4) h27])
, show $
maximumBy (comparing fst) $
withResult (length . hailstone) <$> [1 .. 100000]
]

View file

@ -0,0 +1,53 @@
import Data.List (unfoldr)
hailStones :: Int -> [Int]
hailStones =
(++ [1]) .
unfoldr
(\x ->
if x < 2
then Nothing
else Just
( x
, if even x
then div x 2
else (3 * x) + 1))
mostStones :: Int -> (Int, Int)
mostStones n =
foldr
(\x (m, ml) ->
let l = length (hailStones x)
in if l > ml
then (x, l)
else (m, ml))
(0, 0)
[1 .. n]
-- GENERIC -------------------------------------------------------------------
lastN_ :: Int -> [Int] -> [Int]
lastN_ = (foldr (const (drop 1)) <*>) . drop
-- TEST -----------------------------------------------------------------------
h27, start27, end27 :: [Int]
[h27, start27, end27] = [id, take 4, lastN_ 4] <*> [hailStones 27]
maxNum, maxLen :: Int
(maxNum, maxLen) = mostStones 100000
main :: IO ()
main =
mapM_
putStrLn
[ "Sequence 27 length:"
, show $ length h27
, "Sequence 27 start:"
, show start27
, "Sequence 27 end:"
, show end27
, ""
, "N with longest sequence where N <= 100000"
, show maxNum
, "length of this sequence:"
, show maxLen
]

View file

@ -0,0 +1,58 @@
(() => {
const dctMemo = {};
// Length only of hailstone sequence
// collatzLength :: Int -> Int
const collatzLength = n => {
let i = 1;
let a = n;
let lng;
while (a !== 1) {
lng = dctMemo[a];
if ('u' === (typeof lng)[0]) {
a = (a % 2 ? 3 * a + 1 : a / 2);
i++;
} else return lng + i - 1;
}
return i;
};
// range :: Int -> Int -> Maybe Int -> [Int]
const range = (m, n, delta) => {
const blnUp = n > m,
d = blnUp ? (delta || 1) : -(delta || 1),
lng = Math.abs(Math.floor((blnUp ? n - m : m - n) / d) + 1),
a = Array(lng);
let i = lng;
while (i--) a[i] = (d * i) + m;
return a;
};
// longestBelow :: Int -> {Number::Int, Length:Int}
const longestBelow = n =>
range(1, n)
.reduce(
(a, x) => {
const lng = dctMemo[x] || (dctMemo[x] = collatzLength(x));
return lng > a.l ? {
n: x,
l: lng
} : a
}, {
n: 0,
l: 0
}
);
// TEST
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
return show(
[100000, 1000000, 10000000].map(longestBelow)
);
})();

View file

@ -1,52 +0,0 @@
print "Part 1: Create a routine to generate the hailstone sequence for a number."
print ""
while hailstone < 1 or hailstone <> int(hailstone)
input "Please enter a positive integer: "; hailstone
wend
print ""
print "The following is the 'Hailstone Sequence' for your number..."
print ""
print hailstone
while hailstone <> 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
print hailstone
wend
print ""
input "Hit 'Enter' to continue to part 2...";dummy$
cls
print "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."
print ""
print "No. in Seq.","Hailstone Sequence Number for 27"
print ""
c = 1: hailstone = 27
print c, hailstone
while hailstone <> 1
c = c + 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
print c, hailstone
wend
print ""
input "Hit 'Enter' to continue to part 3...";dummy$
cls
print "Part 3: Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.(But don't show the actual sequence)!"
print ""
print "Calculating result... Please wait... This could take a little while..."
print ""
print "Percent Done", "Start Number", "Seq. Length", "Maximum Sequence So Far"
print ""
for cc = 1 to 99999
hailstone = cc: c = 1
while hailstone <> 1
c = c + 1
if hailstone / 2 = int(hailstone / 2) then hailstone = hailstone / 2 else hailstone = (3 * hailstone) + 1
wend
if c > max then max = c: largesthailstone = cc
locate 1, 7
print " "
locate 1, 7
print using("###.###", cc / 99999 * 100);"%", cc, c, max
scan
next cc
print ""
print "The number less than 100,000 with the longest 'Hailstone Sequence' is "; largesthailstone;". It's sequence length is "; max;"."
end

View file

@ -1,19 +1,11 @@
function x = hailstone(n)
% iterative definition
global VERBOSE;
x = 1;
while (1)
if VERBOSE,
printf('%i ',n); % print element
end;
if n==1,
return;
elseif mod(n,2),
n = 3*n+1;
else
n = n/2;
end;
x = x + 1;
end;
end;
function x = hailstone(n)
x = n;
while n > 1
% faster than mod(n, 2)
if n ~= floor(n / 2) * 2
n = n * 3 + 1;
else
n = n / 2;
end
x(end + 1) = n; %#ok
end

View file

@ -1,4 +1,2 @@
global VERBOSE;
VERBOSE = 1; % display of sequence elements turned on
N = hailstone(27); %display sequence
printf('\n\n%i\n',N); %
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))

View file

@ -1,8 +1,9 @@
global VERBOSE;
VERBOSE = 0; % display of sequence elements turned off
N = 100000;
M = zeros(N,1);
for k=1:N,
M(k) = hailstone(k); %display sequence
end;
[maxLength, n] = max(M)
N = 1e5;
maxLen = 0;
for k = 1:N
kLen = numel(hailstone(k));
if kLen > maxLen
maxLen = kLen;
n = k;
end
end

View file

@ -0,0 +1,18 @@
function [n, maxLen] = longestHailstone(N)
maxLen = 0;
for k = 1:N
a = k;
kLen = 1;
while a > 1
if a ~= floor(a / 2) * 2
a = a * 3 + 1;
else
a = a / 2;
end
kLen = kLen + 1;
end
if kLen > maxLen
maxLen = kLen;
n = k;
end
end

View file

@ -0,0 +1,3 @@
>> [n, maxLen] = longestHailstone(1e5)
n = 77031
maxLen = 351

View file

@ -0,0 +1,22 @@
function [n, maxLen] = longestHailstone(N)
lenList(N) = 0;
lenList(1) = 1;
maxLen = 0;
for k = 2:N
a = k;
kLen = 0;
while a >= k
if a == floor(a / 2) * 2
a = a / 2;
else
a = a * 3 + 1;
end
kLen = kLen + 1;
end
kLen = kLen + lenList(a);
lenList(k) = kLen;
if kLen > maxLen
maxLen = kLen;
n = k;
end
end

View file

@ -0,0 +1,3 @@
>> [n, maxLen] = longestHailstone(1e5)
n = 77031
maxLen = 351

View file

@ -0,0 +1,27 @@
sequence = hailstone(27)
say "Hailstone sequence for 27 has" sequence~items "elements and is ["sequence~toString('l', ", ")"]"
highestNumber = 1
highestCount = 1
loop i = 2 to 100000
sequence = hailstone(i)
count = sequence~items
if count > highestCount then do
highestNumber = i
highestCount = count
end
end
say "Number" highestNumber "has the longest sequence with" highestCount "elements"
-- short routine to generate a hailstone sequence
::routine hailstone
use arg n
sequence = .array~of(n)
loop while n \= 1
if n // 2 == 0 then n = n / 2
else n = 3 * n + 1
sequence~append(n)
end
return sequence

View file

@ -1,37 +0,0 @@
function Hailstone(sys *n)
'=========================
if n and 1
n=n*3+1
else
n=n>>1
end if
end function
function HailstoneSequence(sys n) as sys
'=======================================
count=1
do
Hailstone n
Count++
if n=1 then exit do
end do
return count
end function
'MAIN
'====
maxc=0
maxn=0
e=100000
for n=1 to e
c=HailstoneSequence n
if c>maxc
maxc=c
maxn=n
end if
next
print e ", " maxn ", " maxc
'result 100000, 77031, 351

View file

@ -0,0 +1,37 @@
\newif\ifprint
\newcount\itercount
\newcount\currentnum
\def\hailstone#1{\itercount=0 \currentnum=#1 \hailstoneaux}
\def\hailstoneaux{%
\advance\itercount1
\ifprint\number\currentnum\space\space\fi
\ifnum\currentnum>1
\ifodd\currentnum
\multiply\currentnum3 \advance\currentnum1
\else
\divide\currentnum2
\fi
\expandafter\hailstoneaux
\fi
}
\parindent=0pt
\printtrue\hailstone{27}
Length = \number\itercount
\bigbreak
\newcount\ii \ii=1
\printfalse
\def\lenmax{0}
\def\seed{0}
\loop
\ifnum\ii<100000
\hailstone\ii
\ifnum\itercount>\lenmax\relax
\edef\lenmax{\number\itercount}%
\edef\seed{\number\ii}%
\fi
\advance\ii1
\repeat
Seed max = \seed, length = \lenmax
\bye

View file

@ -1,48 +0,0 @@
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
Shared Hailstones() ; Get access to the Hailstones-List
ClearList(Hailstones()) ; Remove old data
Repeat
AddElement(Hailstones()) ; Add an element to the list
Hailstones()=n ; Fill current value in the new list element
If n=1
ProcedureReturn ListSize(Hailstones())
ElseIf n%2=0
n/2
Else
n=(3*n)+1
EndIf
ForEver
EndProcedure
If OpenConsole()
Define i, l, maxl, maxi
l=FillHailstones(27)
Print("#27 has "+Str(l)+" elements and the sequence is: "+#CRLF$)
ForEach Hailstones()
If i=6
Print(#CRLF$)
i=0
EndIf
i+1
Print(RSet(Str(Hailstones()),5))
If Hailstones()<>1
Print(", ")
EndIf
Next
i=1
Repeat
l=FillHailstones(i)
If l>maxl
maxl=l
maxi=i
EndIf
i+1
Until i>=100000
Print(#CRLF$+#CRLF$+"The longest sequence below 100000 is #"+Str(maxi)+", and it has "+Str(maxl)+" elements.")
Print(#CRLF$+#CRLF$+"Press ENTER to exit."): Input()
CloseConsole()
EndIf

View file

@ -1,34 +0,0 @@
### PART 1:
makeHailstone <- function(n){
hseq <- n
while (hseq[length(hseq)] > 1){
current.value <- hseq[length(hseq)]
if (current.value %% 2 == 0){
next.value <- current.value / 2
} else {
next.value <- (3 * current.value) + 1
}
hseq <- append(hseq, next.value)
}
return(list(hseq=hseq, seq.length=length(hseq)))
}
### PART 2:
twenty.seven <- makeHailstone(27)
twenty.seven$hseq
twenty.seven$seq.length
### PART 3:
max.length <- 0; lower.bound <- 1; upper.bound <- 100000
for (index in lower.bound:upper.bound){
current.hseq <- makeHailstone(index)
if (current.hseq$seq.length > max.length){
max.length <- current.hseq$seq.length
max.index <- index
}
}
cat("Between ", lower.bound, " and ", upper.bound, ", the input of ",
max.index, " gives the longest hailstone sequence, which has length ",
max.length, ". \n", sep="")

View file

@ -1,15 +0,0 @@
> twenty.seven$hseq
[1] 27 82 41 124 62 31 94 47 142 71 214 107 322 161 484
[16] 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700
[31] 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167
[46] 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438
[61] 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051
[76] 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488
[91] 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20
[106] 10 5 16 8 4 2 1
> twenty.seven$seq.length
[1] 112
Between 1 and 1e+05, the input of 77031 gives the longest hailstone sequence,
which has length 351.

View file

@ -1,7 +1,7 @@
/*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.*/
parse arg x y z .; !.h=y /*get optional arguments from the C,L. */
parse arg x y z .; !.h=y /*get optional arguments from the C.L. */
if x=='' | x=="," then x= 27 /*No 1st argument? Then use default.*/
if y=='' | y=="," then y=100000 - 1 /* " 2nd " " " " */
if z=='' | z=="," then z= 12 /*head/tail number? " " " */
@ -24,7 +24,7 @@ hailstone: procedure expose @. !. hm; parse arg n 1 s 1 o,@.1 /*N,S,O: are the
do while @.n==0 /*loop while the residual is unknown. */
parse var n '' -1 L /*extract the last decimal digit of N.*/
if !.L then n=n%2 /*N is even? Then calculate fast ÷ */
else n=n*3 + 1 /*? ? odd ? Then calculate 3*n + 1 */
else n=n*3 + 1 /*" " odd ? " " 3*n + 1 */
s=s n /* [↑] %: is the REXX integer division*/
end /*while*/ /* [↑] append N to the sequence list*/
s=s @.n /*append the number to a sequence list.*/

View file

@ -1,24 +1,24 @@
func hailstone (n) {
var sequence = [n];
var sequence = [n]
while (n > 1) {
sequence.append(
n.is_even ? n.div!(2)
: n.mul!(3).add!(1)
);
sequence << (
n.is_even ? n.div!(2)
 : n.mul!(3).add!(1)
)
}
return(sequence);
return(sequence)
}
 
# The hailstone sequence for the number 27
var arr = hailstone(var nr = 27);
say "#{nr}: #{arr.first(4).to_s} ... #{arr.last(4).to_s} (#{arr.len})";
var arr = hailstone(var nr = 27)
say "#{nr}: #{arr.first(4)} ... #{arr.last(4)} (#{arr.len})"
 
# The longest hailstone sequence for a number less than 100,000
var h = [0, 0];
99_999.times { |i|
var h = [0, 0]
for i (1 .. 99_999) {
(var l = hailstone(i).len) > h[1] && (
h = [i, l];
);
h = [i, l]
)
}
printf("%d: (%d)\n", h...);
 
printf("%d: (%d)\n", h...)

View file

@ -0,0 +1,2 @@
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)) }

View file

@ -0,0 +1,4 @@
[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)))