🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of katrinleinweber

katrinleinweber's solution

to Difference Of Squares in the R Track

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.

Installation

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

How to implement your solution

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.

How to run tests

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.

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.

test_difference-of-squares.R

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)
}

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of phisanti

We have found the same solution!

Avatar of katrinleinweber

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

What can you learn from this solution?

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?