Sum of Series

Numbers around us
Numbers around us
Published in
2 min readNov 6, 2023

Excel BI’s Excel Challenge #318 — solved in R

Defining the Puzzle:

Now we are asked to find sum of small series which value and number depends on input number itself. Sounds weird but it was suprisingly easy and nice.

Find the Sum of the Series — 1*2*3 + 2*3*4 + 3*4*5+…..+N*(N+1)*(N+2)
Hence, if N = 4
Then 1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 = 210
For N = 8
1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 + 5*6*7 + 6*7*8 + 7*8*9 + 8*9*10 = 1980

Loading Data from Excel:

Lets start loading data and libraries:

library(tidyverse)
library(readxl)

input = read_excel(“Sum of Series.xlsx”, range = “A1:A10”)
test = read_excel(“Sum of Series.xlsx”, range = “B1:B10”)

Approach 1: Tidyverse with purrr

sum_of_products = function(N) {
sum(map_dbl(1:N, ~ .x * (.x + 1) * (.x + 2)))
}

result = input %>%
mutate(result = map_dbl(.$N,sum_of_products))

Approach 2: Base R

sum_of_products <- function(N) { sum(sapply(1:N, function(x) x * (x + 1) * (x + 2))) } 
input$result <- sapply(input$N, sum_of_products)

Approach 3: Data.table

As long as Base R and data.table will only differ in way of applying it on data.frame, I’ll drop DT. Sorry guys.

Validation:

identical(test$`Expected Answer`, result$result)
# [1] TRUE

identical(test$`Expected Answer`, input$result)
# [1] TRUE

If you like my publications or have your own ways to solve those puzzles in R, Python or whatever tool you choose, let me know.

--

--

Numbers around us
Numbers around us

Self developed analyst. BI Developer, R programmer. Delivers what you need, not what you asked for.