Project Eueler: problem14

問題

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?

回答

def cnt_chain(n)
  cnt = 0
  loop do
    cnt += 1
    break if n == 1
    if n % 2 == 0
     n = n / 2
    else
     n = 3*n + 1
    end
  end
  return cnt
end

max_cnt, max_start = 0, 0
1.upto(1000000) do |num|
 now = cnt_chain(num)
  if now > max_cnt
    max_cnt = now
    max_start = num
  end
end

p "max_cnt = #{max_cnt}"
p "max_start = #{max_start}"

備考

10分ぐらいかかる。遅い。

この問題はコラッツの問題というらしい。
配列にキャッシュすることで高速化できるのか。
(参考)
http://d.hatena.ne.jp/ha-tan/20080401/1207229173