Problem Description
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:
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.
Analysis
Brute forcing a solution may break the one minute rule especially if the limit of this problem changes. Two ways we improved the performance to mere seconds was to cache the chain lengths and only check odd n from half the range, in this case 500,001 to 1,000,000. We can do this because the results are symmetrical either side of the half-way point.
Solution
Runs < 3 seconds in Python.
cache = { 1: 1 } def chain(n): if not n in cache: cache[n] = chain(3*n+1 if n%2 else n/2) + 1 return cache[n] max = (0,0) for i in range(500001,1000000,2): if chain(i) > max[1]: max = (i,chain(i)) print "Answer to PE14 = ", max
Comments
This solution prints both the starting number and chain length





Discussion
No comments for “Project Euler Problem 14 Solution”