Done puzzle 28
[project-euler.git] / euler14.rb
1 require 'logger'
2 log = Logger.new(STDERR)
3 log.level = Logger::WARN
4
5 $chain_lengths = {1 => 1}
6
7 def chain_length(n)
8 unless $chain_lengths.has_key?(n)
9 if n % 2 == 0
10 $chain_lengths[n] = 1 + chain_length(n / 2)
11 else
12 $chain_lengths[n] = 1 + chain_length(3 * n + 1)
13 end
14 end
15 $chain_lengths[n]
16 end
17
18 longest_chain_start = 1
19 1.upto(1000000) do |i|
20 if chain_length(i) > chain_length(longest_chain_start)
21 longest_chain_start = i
22 log.info {"Found new longest chain. Starts at #{i}, #{chain_length(i)} elements"}
23 end
24 log.debug {"#{i} has chain length #{chain_length(i)}"}
25 end
26
27 puts "Longest chain starts at #{longest_chain_start}, with #{$chain_lengths[longest_chain_start]} elements"
28
29 log.close