ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

Published at Jul 13 2018
·
2 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.

See this guide for instructions on how to setup your local R environment.

In each problem folder, there is a file named `<exercise_name>.R`

containing a function that returns a `NULL`

value. Place your implementation inside the body of the function.

Inside of RStudio, simply execute the `test_<exercise_name>.R`

script. This can be conveniently done with testthat's `auto_test`

function. Because exercism code and tests are in the same folder, use this same path for both `code_path`

and `test_path`

parameters. On the command-line, you can also run `Rscript test_<exercise_name>.R`

.

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.

```
source("./difference-of-squares.R")
library(testthat)
context("difference of squares")
test_that("difference of squares 0", {
input <- 0
expect_equal(difference_of_squares(input), 0)
})
test_that("difference of squares 5", {
input <- 5
expect_equal(difference_of_squares(input), 170)
})
test_that("difference of squares 10", {
input <- 10
expect_equal(difference_of_squares(input), 2640)
})
test_that("difference of squares 100", {
input <- 100
expect_equal(difference_of_squares(input), 25164150)
})
message("All tests passed for exercise: difference-of-squares")
```

```
difference_of_squares <- function(natural_number) {
sum(1:natural_number)^2 - sum((1:natural_number)^2)
}
```

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

We have found the same solution!

Well, it's a centuries old calculation. Our teachers might have used the same textbooks ;-)