Avatar of 4d47
0
0
Genius
0
0

4d47's solution

to Difference Of Squares in the Emacs Lisp Track

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.

Source

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

Submitting Incomplete Solutions

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

difference-of-squares-test.el

;;; difference-of-squares-test.el --- Tests for difference-of-squares (exercism)

;;; Commentary:

;;; Code:

(load-file "difference-of-squares.el")

(ert-deftest square-of-sums-to-5 ()
  (should (= 225 (square-of-sums 5))))

(ert-deftest sum-of-squares-to-5 ()
  (should (= 55 (sum-of-squares 5))))

(ert-deftest difference-of-sums-to-5 ()
  (should (= 170 (difference 5))))


(ert-deftest square-of-sums-to-10 ()
  (should (= 3025 (square-of-sums 10))))

(ert-deftest sum-of-squares-to-10 ()
  (should (= 385 (sum-of-squares 10))))

(ert-deftest difference-of-sums-to-10 ()
  (should (= 2640 (difference 10))))


(ert-deftest square-of-sums-to-100 ()
  (should (= 25502500 (square-of-sums 100))))

(ert-deftest sum-of-squares-to-100 ()
  (should (= 338350 (sum-of-squares 100))))

(ert-deftest difference-of-sums-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

What can you learn from this solution?

A huge amount can be learnt 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 I could read more about to develop my understanding?