Problem 12 (written in Ruby)

こいつは手強かった。
普通にやると計算爆発を起こして数十分単位の時間が必要になります。
三角数の数学的な性質を使うと1分以内に解けるようになりました。


def factors(n)
ret = []
1.upto(n) do |i|
ret << i if n % i == 0
end
return ret
end

tn = 0
i = 0
prev = [1,2]
while true do
i += 1
tn += i

fac = factors(i+1)
tn_fac = fac.map{|x|prev.map{|y|x*y}}.flatten.select{|n|n<=tn}.select{|n|tn%n==0}
prev = fac

if 500 < tn_fac.size then
puts "FOUND: tn=#{tn} i=#{i}"
tn_fac.sort.each_with_index do |tnf, index|
puts "#{index}: #{tnf}"
end
break
end
end

Problem:
http://odz.sakura.ne.jp/projecteuler/index.php?Problem%2012