Hailstone sequence: Difference between revisions
Content added Content deleted
imported>Chinhouse |
|||
Line 6,671: | Line 6,671: | ||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
==Non-cached version== |
|||
Calculates sequence without using previous calculated sequences. |
|||
<syntaxhighlight lang="miniscript"> |
<syntaxhighlight lang="miniscript"> |
||
getSequence = function(n) |
getSequence = function(n) |
||
Line 6,712: | Line 6,715: | ||
The number < 100,000 which has the longest hailstone sequence is 77031. |
The number < 100,000 which has the longest hailstone sequence is 77031. |
||
This sequence has 351 elements.</pre> |
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:] |
|||
print |
|||
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 |
|||
</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|ML}}== |
||
==={{header|MLite}}=== |
==={{header|MLite}}=== |