Hailstone sequence: Difference between revisions

Content added Content deleted
imported>Chinhouse
imported>Chinhouse
Line 6,730: Line 6,730:
n = n /2
n = n /2
end if
end if
items.push(n)
items.push n
end while
end while
cache[origNum] = {"len": items.len,"items":items}
cache[origNum] = {"len": items.len,"items":items}
Line 6,736: Line 6,736:


getLen = function(n)
getLen = function(n)
if not cache.hasIndex(n) then calc(n)
if not cache.hasIndex(n) then calc n
if n == 1 then return 1
if n == 1 then return 1
return cache[n].len + getLen(cache[n].items[-1]) - 1
return cache[n].len + getLen(cache[n].items[-1]) - 1
Line 6,742: Line 6,742:


getSequence = function(n)
getSequence = function(n)
if not cache.hasIndex(n) then calc(n)
if not cache.hasIndex(n) then calc n
if n == 1 then return [1]
if n == 1 then return [1]
return cache[n].items[:-1] + getSequence(cache[n].items[-1])
return cache[n].items[:-1] + getSequence(cache[n].items[-1])
Line 6,752: Line 6,752:
print "and ending with"
print "and ending with"
print h[-4:]
print h[-4:]

print


longSeq = 0
longSeq = 0
Line 6,764: Line 6,762:
end if
end if
end for
end for
print "The number < 100,000 which has the longest hailstone sequence is " + longSeqVal + "."
print "This sequence has " + longSeq + " elements."
</syntaxhighlight>
</syntaxhighlight>