Python Implementation of Problem 14

View source code here on GitHub!

Problem Solution

Project Euler Problem 14

I did a naive approach where I just built the whole sequence.

Revision 1:

I reformulated this to build a sequence length instead of the sequence. Should use less memory and take less time.

Problem:

The following iterative sequence is defined for the set of positive integers:

n → n/2 (n is even) n → 3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

NOTE: Once the chain starts the terms are allowed to go above one million.

python.src.p0014.collatz_len(n: int, cache: MutableMapping[int, int]) int
python.src.p0014.main() int
 1"""
 2Project Euler Problem 14
 3
 4I did a naive approach where I just built the whole sequence.
 5
 6Revision 1:
 7
 8I reformulated this to build a sequence length instead of the sequence. Should
 9use less memory and take less time.
10
11Problem:
12
13The following iterative sequence is defined for the set of positive integers:
14
15n → n/2 (n is even)
16n → 3n + 1 (n is odd)
17
18Using the rule above and starting with 13, we generate the following sequence:
1913 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
20
21It can be seen that this sequence (starting at 13 and finishing at 1) contains
2210 terms. Although it has not been proved yet (Collatz Problem), it is thought
23that all starting numbers finish at 1.
24
25Which starting number, under one million, produces the longest chain?
26
27NOTE: Once the chain starts the terms are allowed to go above one million.
28"""
29from typing import MutableMapping
30
31
32def collatz_len(n: int, cache: MutableMapping[int, int]) -> int:
33    if n in cache:
34        return cache[n]
35    if n == 1:
36        result = 0
37    elif n & 1 == 0:
38        result = 1 + collatz_len(n // 2, cache)
39    else:
40        result = 2 + collatz_len((3 * n + 1) // 2, cache)
41    cache[n] = result
42    return result
43
44
45def main() -> int:
46    cache: MutableMapping[int, int] = {}
47    return max(
48        (collatz_len(x, cache), x) for x in range(1, 1000000)
49    )[1]

Tags: collatz, recursion, longest-path