Exercism v3 launches on Sept 1st 2021. Learn more! ðŸš€ðŸš€ðŸš€

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.

```
;; Load SRFI-64 lightweight testing specification
(use-modules (srfi srfi-64))
;; Suppress log file output. To write logs, comment out the following line:
(module-define! (resolve-module '(srfi srfi-64)) 'test-log-to-file #f)
;; Require module
(add-to-load-path (dirname (current-filename)))
(use-modules (squares))
(test-begin "difference-of-squares")
(test-eqv "square-of-sums-to-5"
225
(square-of-sums 5))
(test-eqv "sum-of-squares-to-5"
55
(sum-of-squares 5))
(test-eqv "difference of-sums-to-5"
170
(difference 5))
(test-eqv "square-of-sums-to-10"
3025
(square-of-sums 10))
(test-eqv "sum-of-squares-to-10"
385
(sum-of-squares 10))
(test-eqv "difference of-sums-to-10"
2640
(difference 10))
(test-eqv "square-of-sums-to-100"
25502500
(square-of-sums 100))
(test-eqv "sum-of-squares-to-100"
338350
(sum-of-squares 100))
(test-eqv "difference of-sums-to-100"
25164150
(difference 100))
(test-end "difference-of-squares")
```

```
(define-module (squares)
#:export (sum-of-squares
square-of-sums
difference)
#:autoload (srfi srfi-1) (fold iota))
(define (square-of-sums n)
(expt (fold + 0 (iota n 1)) 2))
(define (sum-of-squares n)
(fold (lambda (x y)
(+ (expt x 2) y)) 0 (iota n 1)))
(define (difference n)
(- (square-of-sums n) (sum-of-squares n)))
```

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?

Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments