Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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

### Defining the Puzzle:

In current puzzle we need to check if digits of our numbers has some magic properties. Seems easy, but it is not usually the case, when ExcelBI prepare riddle.

List all Sumproduct numbers from column A.
A Sum product number is that number which is perfectly divisible by both the sum of digits and product of digits.
Ex. 135 which is perfectly divisible by both 1+3+5=9 and 1*3*5 = 15

library(tidyverse)
library(data.table)

input = read_excel(“Sumproduct Number.xlsx”, range = “A1:A10”)
test = read_excel(“Sumproduct Number.xlsx”, range = “B1:B3”)

### Approach 1: Tidyverse with purrr

is_sum_product_tv = function(number){
digits = as.numeric(str_split(as.character(number), “”)[[1]])
sum = reduce(digits, `+`)
product = reduce(digits, `*`)

check = number %% sum == 0 & number %% product == 0
return(check)
}

result_tv = input %>%

### Approach 2: Base R

is_sum_product_base <- function(number) {
digits <- as.numeric(unlist(strsplit(as.character(number), “”)))

sum_digits <- sum(digits)
product_digits <- prod(digits)

check <- number %% sum_digits == 0 & number %% product_digits == 0
return(check)
}

result_base <- vector(“list”, length = nrow(input))
for (i in seq_along(input\$Number)) {
result_base[[i]] <- is_sum_product_base(input\$Number[i])
}

### Approach 3: Data.table

input_dt = setDT(input)
is_sum_product_dt <- function(number) {
digits <- as.numeric(unlist(strsplit(as.character(number), “”)))
sum_digits <- sum(digits)
product_digits <- prod(digits)
check <- number %% sum_digits == 0 & number %% product_digits == 0
return(check)
}

result_dt <- input_dt[my_answer == TRUE, .(Number)]

### Validating Our Solutions:

#[1] TRUE
#[1] TRUE
#[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.

Sumproduct number was originally published in Numbers around us on Medium, where people are continuing the conversation by highlighting and responding to this story.