Problem 14: Find the longest sequence
The problem is:
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.
I just brute forced it. I did take a guess that the number would be in the 500k to 1m range. It takes about 40 seconds. It runs in about 16 seconds if I use only odd numbers between 500001 and 1m. Is there a better way?
Anyway, the code:
%%
% Problem 14 (a bit slow (40 seconds ish) maybe I could add a cache??)
% Note1: optimised after reading the forum to only use the odd numbers
%%
prob14() ->
L = lists:seq(500001, 1000000, 2),
max(lists:map(fun(X) -> {X, length(get_next([X]))} end, L), {0, 0}).
max([], Max) -> Max;
max([{_X, Len}=H|T], {_MaxX, MaxLen}=Max) ->
case Len > MaxLen of
true ->
max(T, H);
false ->
max(T, Max)
end.
get_next([H|T]=L) when H rem 2 =:= 0 ->
get_next([H div 2|L]);
get_next([H|T]=L) when H =:= 1 ->
L;
get_next([H|T]=L) ->
get_next([(3 * H) + 1|L]).
Some people on the forum are getting there results in ~1-5 seconds which is a whole load faster than mine. Some are doing that by using a cache and others by using what appears to be faster implementations. I guess my Erlang solution is slow because I don't know the right way to write Erlang.
I also think (for learning purposes) I'll try and do a multi-process version of this solution since it decomposes well into that idiom.