Using only basic control structures¶

In [6]:
n = 7051041254675900751362702445531870301022307
biggest_so_far = n
while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3*n+1
    
    if n > biggest_so_far:
        biggest_so_far = n

biggest_so_far
Out[6]:
31729685646041553381132161004893416354600384

Using a generator¶

Note the use of yield instead of return, which turns collatz_sequence into a generator.

As with any Iterable, one can use many native tools on a generators, like min, or as here, max.

In [7]:
def collatz_next(n):
    """return the next number in the Collatz sequence"""
    return n//2 if n % 2 == 0 else 3*n+1

def collatz_sequence(n):
    """A generator for the Collatz sequence starting at n"""
    yield n
    while n != 1:
        n = collatz_next(n)
        yield n
        
max(collatz_sequence(7051041254675900751362702445531870301022307))
Out[7]:
31729685646041553381132161004893416354600384