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

# katrinleinweber's solution

## to Sum Of Multiples in the R Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Given a number, find the sum of all the unique multiples of particular numbers up to but not including that number.

If we list all the natural numbers below 20 that are multiples of 3 or 5, we get 3, 5, 6, 9, 10, 12, 15, and 18.

The sum of these multiples is 78.

## 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

A variation on Problem 1 at Project Euler http://projecteuler.net/problem=1

## Submitting Incomplete Solutions

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

### test_sum-of-multiples.R

``````source("./sum-of-multiples.R")
library(testthat)

context("sum of multiples")

test_that("Case 1", {
expect_equal(sum_of_multiples(c(3, 5), 1), 0)
})

test_that("Case 2", {
expect_equal(sum_of_multiples(c(3, 5), 4), 3)
})

test_that("Case 3", {
expect_equal(sum_of_multiples(c(3, 5), 10), 23)
})

test_that("Case 4", {
expect_equal(sum_of_multiples(c(3, 5), 100), 2318)
})

test_that("Case 5", {
expect_equal(sum_of_multiples(c(3, 5), 1000), 233168)
})

test_that("Case 6", {
expect_equal(sum_of_multiples(c(7, 13, 17), 20), 51)
})

test_that("Case 7", {
expect_equal(sum_of_multiples(c(4, 6), 15), 30)
})

test_that("Case 8", {
expect_equal(sum_of_multiples(c(5, 6, 8), 150), 4419)
})

test_that("Case 9", {
expect_equal(sum_of_multiples(c(5, 25), 51), 275)
})

test_that("Case 10", {
expect_equal(sum_of_multiples(c(43, 47), 10000), 2203160)
})

test_that("Case 11", {
expect_equal(sum_of_multiples(c(1), 100), 4950)
})

test_that("Case 12", {
expect_equal(sum_of_multiples(c(), 10000), 0)
})

message("All tests passed for exercise: sum-of-multiples")``````
``````sum_of_multiples <- function(factors, limit) {

# create vector of candidate integers
candidates <- seq(limit - 1)

# narrow candidates down to factors & unique multiples
multiples <- c()
for (f in factors)
for (c in candidates)
if (c %% f == 0 & !(c %in% multiples))
multiples <- append(multiples, c)
# [ ] recursive append?
# [ ] purrr::map or ::walk on differently long vectors?

# sum those up
sum(multiples)

}``````