Published at Jul 13 2018
·
0 comments

Instructions

Test suite

Solution

Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.

The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)² = 55² = 3025.

The sum of the squares of the first ten natural numbers is 1² + 2² + ... + 10² = 385.

Hence the difference between the square of the sum of the first ten natural numbers and the sum of the squares of the first ten natural numbers is 3025 - 385 = 2640.

Problem 6 at Project Euler http://projecteuler.net/problem=6

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
;;; difference-of-squares-test.el --- Tests for difference-of-squares (exercism)
;;; Commentary:
;;; Code:
(load-file "difference-of-squares.el")
(ert-deftest square-of-sum-to-5 ()
(should (= 225 (square-of-sum 5))))
(ert-deftest sum-of-squares-to-5 ()
(should (= 55 (sum-of-squares 5))))
(ert-deftest difference-of-squares-to-5 ()
(should (= 170 (difference 5))))
(ert-deftest square-of-sum-to-10 ()
(should (= 3025 (square-of-sum 10))))
(ert-deftest sum-of-squares-to-10 ()
(should (= 385 (sum-of-squares 10))))
(ert-deftest difference-of-squares-to-10 ()
(should (= 2640 (difference 10))))
(ert-deftest square-of-sum-to-100 ()
(should (= 25502500 (square-of-sum 100))))
(ert-deftest sum-of-squares-to-100 ()
(should (= 338350 (sum-of-squares 100))))
(ert-deftest difference-of-squares-to-100 ()
(should (= 25164150 (difference 100))))
(provide 'difference-of-squares-test)
;;; difference-of-squares-test.el ends here
```

```
;;; difference-of-squares.el --- Difference of Squares (exercism)
;;; Commentary:
;;; Code:
(defun difference (n)
(- (square-of-sums n) (sum-of-squares n)))
(defun square-of-sums (n)
(square (apply '+ (number-sequence 1 n))))
(defun sum-of-squares (n)
(apply '+ (mapcar 'square (number-sequence 1 n))))
(defun square (n)
(expt n 2))
(provide 'difference-of-squares)
;;; difference-of-squares.el ends here
```

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

- What compromises have been made?
- Are there new concepts here that you could read more about to improve your understanding?

## Community comments