Powerful Numbers

[This article was first published on Numbers around us - Medium, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
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 #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.


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

To leave a comment for the author, please follow the link and comment on their blog: Numbers around us - Medium.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)