# Project Euler #6 in Ruby

Question:

Difference between the Sum of squares from 1 to 100 and the square of sums of 1 to 100.

range.inject(:+) ** 2 - range.map{|x| x ** 2}.inject(:+)


This one seems pretty straightforward but welcome any improvements to make it more elegant!

The elegance of Mathematics:

def sum_below(n)
n * (n + 1) / 2
end

def sum_squares_below(n)
n * (n + 1) * (2*n + 1) / 2
end

limit = 1000
puts sum_below(limit) ** 2 - sum_squares_below(limit)


## The Math under n * (n + 1) / 2

We have some natural numbers and we want to find their sum, the list is:

1, 2, 3, 4 ... n


Now we can note that the sum of n + 1 is equal to the sum (n - 1) + (1 + 1) and is in turn equal to (n - 1 - 1) + (1 + 1 + 1). In practice in the following

1, 2, 3, 4, 5, 6


We can see that 1 + 6 == 2 + 5 == 3 + 4 == 7.

We must repeat this (sum that equals n + 1) (n / 2) times so we arrive to the final formula:

sum_below(n) = (n + 1) * n / 2

• Shouldn't the sum_squares_below actually be n * (n + 1) * (2*n + 1) / 6 ? Commented Jul 28, 2016 at 21:52