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.

ソース

class Integer
	@@cache = {}
	def collatz
		self % 2 == 0 ? self / 2 : self * 3 + 1
	end
	def collatz_count
		return @@cache[self] unless @@cache[self].nil?
		return 1 if self == 1
		@@cache[self] = self.collatz.collatz_count + 1
	end
end

max = 0
num = 0
(1..1000000).each do |i|
	count = i.collatz_count
	num, max = i, count if max < count
end

puts "#{num}(#{max})"

解答

括弧内は項の数を示す。

837799(525)

感想

何となく綺麗に出来た
キャッシュする部分が問題の鍵かな?