最終更新: 2014-07-18T23:16+0900
Project Eulerどうなってしまうん?(攻撃されて DBが信用できなくなってログインなどの操作ができないまま問題だけが再び公開されてる)
#!rubyw
# coding: utf-8
# 11) Product and Sum
#
# Challenge: I’ve written down all the integers from 1 to 65,502 inclusive. I select two of them, cross them
# out, and multiply them together to get a product. When I sum up the remaining 65,500 numbers, I get the
# same result. What two numbers did I pick?
SUM_OF_65502 = 65502 * 65503 / 2
1.upto(65502) {|n|
(n+1).upto(65502) {|m|
p [n,m] if n*m == SUM_OF_65502-n-m
}
} unless "repeat (65502 * 65501 / 2) times."
# if n*m == SUM_OF_65502-n-m
# ⇔ if (n+1)*(m+1) == SUM_OF_65502+1
1.upto(65502) {|n|
q, r = *(SUM_OF_65502+1).divmod(n+1)
m = q-1
next unless m <= 65502 # nの定義域の下限を選ぶことで不要にできる。off-by-oneエラーを避けられないからやらない。
break unless n < m # nの定義域の上限を選ぶことで不要にできる。そのために Math.sqrtを使うなら、このままとどちらが良いか? そしてここでも off-by-one. n+1と m+1に別の文字を割り当ててそれらの関係と定義域をコードにすべきだろう。
p [n,m] if 0 == r
}
p Process.times