Rubyでサムオブスクエアスクエアオブサム 〜Rubyでオイラープロジェクトを解こう!Problem6
The sum of the squares of the first ten natural numbers is,
The square of the sum of the first ten natural numbers is,
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
最初の10個の自然数を二乗したものの合計は、
最初の10個の自然数の合計を二乗したものは、
よってこれらの差は、3025 - 385 = 2640である。
最初の100個の自然数を二乗したものの合計と、それら自然数の合計を二乗したものとの差を求めよ。
def sum_of_squares(limit) sum = 0 1.upto(limit) do |n| sum += n ** 2 end sum end def square_of_sum(limit) (1..limit).to_a.inject(:+) ** 2 end limit = 100 (sum_of_squares(limit) - square_of_sum(limit)).abs # => 25164150