Project Euler

Problem #14

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.

Erlang: Running time = 7.133s
p14_search(Parent)->
	put(1,1),
	lists:foreach(fun(X)->p14_search(X,Parent) end, lists:seq(1,999999)),
	Parent! done.
p14_search(N,Parent)->
	case get(N) of
		undefined->
			Val=1+case N band 1 of 0-> p14_search(N div 2, Parent); 1->p14_search(1+3*N,Parent) end,
			put(N,Val),
			Parent ! {N,Val},
			Val;
		SomeNum->SomeNum
	end.

p14()->
	spawn(euler, p14_search, [self()]),
	p14_wait({0,0}).

p14_wait({Highest,Value})->
	receive
		done->io:format("~w~n",[Highest]);
		{High,Val} when Val > Value, High < 1000000->p14_wait({High,Val});
		_Else ->p14_wait({Highest,Value})
	end.

Ruby: Running time = 13.64s
def p14recur(hash,i)
  return hash[i] if hash[i]
  hash[i]=1+p14recur(hash,i/2) if i%2==0
  hash[i]=1+p14recur(hash,3*i+1) if i%2==1
  return hash[i]
end

def p14
  vals={1=>1}
  1.upto(999999){|i|p14recur(vals,i)}
  puts vals.index(vals.values.max)
end