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."