Powerful Numbers
Excel BI’s Excel Challenge #319 — solved in R
Defining the Puzzle:
We need to find which from given numbers are “more powerful” than others which means as follow:
List all Powerful numbers.
A powerful is number is that number which is perfectly divisible by square of all its Prime factors.
Ex. 225 — Prime factors are 3 and 5. In turn, 225 is perfectly divided by both 3*3 and 5*5.
Loading Data from Excel:
Lets start loading data and libraries:
library(tidyverse)
library(primes)
library(readxl)
library(data.table)
input = read_excel(“Powerful Numbers.xlsx”, range = “A1:A10”)
test = read_excel(“Powerful Numbers.xlsx”, range = “B1:B6”)
Approach 1: Tidyverse with purrr
is_powerful = function(number) {
vec_primes = prime_factors(number)
count_vec = vec_primes %>% as.data.frame() %>% select(num = 1) %>% group_by(num) %>%
summarise(a = n())
check = all(count_vec$a > 1)
return(check)
}
result = input %>%
mutate(is_powerful = map(Numbers, is_powerful)) %>%
filter(is_powerful == TRUE) %>%
select(Numbers)
Approach 2: Data.table
We will use exactly the same so today, so only method of calling it changes. So today DT version is up.
setDT(input)
input[, is_powerful := sapply(Numbers, is_powerful)]
result <- input[is_powerful == TRUE, .(Numbers)]
Validating Our Solutions:
identical(result$Numbers, test$`Answer Expected`)
# [1] TRUE
identical(test$`Answer Expected`, result$Numbers)
# [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.