# -*- coding: utf-8 -*- # http://odz.sakura.ne.jp/projecteuler/index.php?cmd=read&page=Problem%2042 # # SKY = 19 + 11 + 25 # から,単語のスコアは, # A = 1, B = 2 .. # だと思われる.. # # 三角数の式 # t(n) = 1/2 * n * (n + 1) # # から逆関数は def t_inv(t) (Math.sqrt(8.0 * t + 1.0) - 1.0 ) / 2.0 end # 逆関数の出力が整数であれば与えられた整数は三角数である. def triangle_number?(n) n = t_inv(n) n == n.to_i end # ファイルの単語のうち三角語を数える. puts File.read("words.txt").split(",").map{|w| w.gsub(/["\s]+/, '')}.reduce(0) {|count, word| count + (triangle_number?(word.bytes.reduce(0) {|sum, c| sum + (c - 64) }) ? 1 : 0) }