Euler Project 14 Longest Collatz Sequence I have been working through the euler project and I have created the following code for Problem 14, which asks which starting number, under 1 million, produces the longest Collatz Sequence chain.

It takes a good minute to process.  Can I make it faster?

class Collatz:

    def __init__(self):
        self.c = 1

    def if_even(self, n):
        return int(n / 2)

    def if_odd(self, n):
        return int(n * 3 + 1)

    def decide(self, n):
        if (n &amp; 1) == 0:
            return self.if_even(n)
        elif (n &amp; 1) == 1:
            return self.if_odd(n)

    def iter_nums(self, n):
        if n == 1:
            return n
        self.c += 1
        n = self.decide(n)    
        self.iter_nums(n)

largest = 0

# col = Collatz()
# col.iter_nums(13)

# print(col.c)


for i in range(1000000, -1, -1):
    col = Collatz()
    col.iter_nums(i)
    if col.c &gt; largest:
        largest = i

print(largest)
Useless calls to int

When n is an integer:


n * 3 + 1 is an integer as well, you don't need to call int
int(n / 2) can also be computed using the "floored quotient" with the // operator.


You don't need a class

I highly recommend watching Jack Diederich's talk called "Stop Writing Classes". Classes are a great tool but they are not always needed, sometimes the problem can be solved with simple tools like functions.

In your case, the whole class can be restricted to a simple function, shorter, clearer, more efficient, easier to use.

def get_collatz_length(n):
    if n == 1:
        return 1
    return 1 + get_collatz_length((3 * n + 1) if (n &amp; 1) else n // 2)


You don't need recursion

Once again, recursion can be a great way to write a concise solution for a given problem. However, in Python, it is sometimes best to avoid it: there is no tail-recursion optimisation and the call stack has a fairly limited size.

You could write something like:

def get_collatz_length_loop(n):
    l = 1
    while n != 1:
        n = (3 * n + 1) if (n &amp; 1) else n // 2
        l += 1
    return l


To be continued: memoization

Is bitwise optimisation relevant?