I solved Euler problem 14 but the program I used is very slow. I had a look at what the others did and they all came up with elegant solutions. I tried to understand their code without much success.

Here is my code (the function to determine the length of the Collatz chain

```
def collatz(n):
a=1
while n!=1:if n%2==0:n=n/2else:n=3*n+1a+=1
return a
```

Then I used brute force. It is slow and I know it is weak. Could someone tell me why my code is weak and how I can improve my code in plain English.
Bear in mind that I am a beginner, my programming skills are basic.

Rather than computing every possible chain from the start to the end, you can keep a cache of chain starts and their resulting length. For example, for the chain

```
13 40 20 10 5 16 8 4 2 1
```

you could remember the following:

- The Collatz chain that starts with 13 has length 10
- The Collatz chain that starts with 40 has length 9
- The Collatz chain starting with 20 has length 8

... and so on.

We can then use this saved information to stop computing a chain as soon as we encounter a number which is already in our cache.

### Implementation

Use dictionaries in Python to associate starting numbers with their chain length:

```
chain_sizes = {}
chain_sizes[13] = 10
chain_sizes[40] = 9
chain_sizes[40] # => 9
20 in chain_sizes # => False
```

Now you just have to adapt your algorithm to make use of this dictionary (filling it with values as well as looking up intermediate numbers).

By the way, this can be expressed very nicely using recursion. The chain sizes that can occur here will not overflow the stack :)