lavaboom
4/2/2015 - 6:59 AM

Longest Collatz sequence (Euler #14)

Longest Collatz sequence (Euler #14)

def collatz(n, result=[]):    
    if n < 0: raise ValueError
    else: result.append(int(n))

    if n == 1: return result

    if n % 2 == 0:
        return collatz(n / 2, result=result)
    else: 
        return collatz(3 * n + 1, result=result)

def max_collatz(n):
    cur_max = 0
    result = n
    for i in range(n - 1, 1, -2):
        a = len(collatz(i, result=[]))
        if a > cur_max:
            cur_max = a
            result = i
    return result

print(max_collatz(10**6))