Revisiting the Collatz Sequence – Laurent Rosenfeld
FWIW, the following Python code has about the same run-time. (The raw numbers are a bit faster on my machine than the reported numbers, but that means little given the unknown difference between the machines.)<p><pre><code>    # http:&#x2F;&#x2F;blogs.perl.org&#x2F;users&#x2F;laurent_r&#x2F;2020&#x2F;04&#x2F;revisiting-the-collatz-sequence-pwc-54.html

    # If the previous term is even, the next term is one half of the
    # previous term. If the previous term is odd, the next term is 3 times
    # the previous term plus 1

    # Calculate the sequence length for all starting numbers up to 1000000
    # and output the starting number and sequence length for the longest
    # 20 sequences.

    import heapq

    def main():
        MAX =  1_000_000 #  0.78 seconds
        #MAX = 10_000_000 #  8.2 seconds

        arr = [0] * MAX # cache Collatz length for a given number. 0 = not computed
        arr[0] = -1
        arr[1] = 1

        for i in range(2, MAX):
            if arr[i]:   # Already computed. Go to the next one.
                continue

            values = [i] # Keep track of the missing terms
            while 1:
                if i % 2:
                    i = i*3+1
                else:
                    i &#x2F;&#x2F;= 2
                if i &lt; MAX and arr[i]:
                    # Found a hit. Back-fill the missing parts.
                    n = arr[i] + 1
                    values.reverse()
                    for val in values:
                        if val &lt; MAX:
                            arr[val] = n
                        n += 1
                    break
                values.append(i) # Extend the sequence

        # Report the top 20
        for i in heapq.nlargest(20, range(MAX), key=arr.__getitem__):
            print(i, arr[i])

    if __name__ == &quot;__main__&quot;:
        import time
        t1 = time.time()
        arr = main()
        t2 = time.time()
        print(f&quot;{t2-t1:.2} seconds&quot;)</code></pre>