def chain_length(n, chains):
    """ Return the chain length of a number n.
        If the chain length of n isn't stored yet, then calculate it according
        to the collatz sequence rules recursively and store it for future
        reference. Also store all the chain lengths for numbers that are found
        during the recursive iterations.
    """
    if not n in chains:
        chains[n] = 1 + chain_length(n/2 if n%2==0 else n*3+1, chains)
    return chains[n]