4
\$\begingroup\$

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!

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Apr 3, 2015 at 16:45
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
answered Apr 3, 2015 at 18:54
\$\endgroup\$
1
  • \$\begingroup\$ Shouldn't the sum_squares_below actually be n * (n + 1) * (2*n + 1) / 6 ? \$\endgroup\$ Commented Jul 28, 2016 at 21:52

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.