Project Euler - Problem 14 - Longest Collatz sequence
coding algo projecteulerProblem
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.
Solution
Naive Solution
My first naive solution was brute force.
def getCollatz(n):
i = 1
while n>1:
if n%2: n = 3*n+1
else: n = n/2
i += 1
return i
max = 0; start = 0
for i in range(int(1e6)):
collatz = getCollatz(i)
if collatz>max: max = collatz; start=i
print max, start
It ran for around 24.979 seconds.
Improved version
Afterwards, I implemented a hash to store the result, so there is no need to go over the whole list of numbers again and again.
hash = {}
def getCollatz(n):
global hash
i = 1; s = n; seq = []
while n>1:
if hash.get(n): i += hash[n]; n=0
seq.append(n)
if n%2: n = 3*n+1
else: n = n/2
i += 1
for idx, j in enumerate(seq): hash[j] = i-idx
return i
max = 0; start = 0
for i in range(int(1e6)):
collatz = getCollatz(i)
if collatz>max: max = collatz; start=i
print max, start
It ran for 4.099 seconds, 6 times improvement.