Question:
Difference between the Sum of squares from 1 to 100 and the square of sums of 1 to 100.
Answer in Ruby:
range.inject(:+) ** 2 - range.map{|x| x ** 2}.inject(:+)
This one seems pretty straightforward but welcome any improvements to make it more elegant!
1 Answer 1
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
-
\$\begingroup\$ Shouldn't the sum_squares_below actually be n * (n + 1) * (2*n + 1) / 6 ? \$\endgroup\$Sakamoto Kazuma– Sakamoto Kazuma2016年07月28日 21:52:01 +00:00Commented Jul 28, 2016 at 21:52