Semi Prime Numbers

Numbers around us
Numbers around us
Published in
2 min readOct 18, 2023

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

Defining the Puzzle

We are getting back to checking numbers properties with ExcelBI. Today we have some numbers to determine if they are Semi Prime. Post with riddle is here.

List all Semi Prime Numbers.
A Semi Prime is a natural number that is the product of exactly two prime numbers
Ex. 314 which can be expressed as product of two prime numbers — 2 and 157

I would add that Semi Prime number has 4 factors: 1, itself and two which are not 1 or itself, but both are prime numbers themselves.

Loading Exercise

Today we are going to load something from Excel file to check. But as I realized there are some really big numbers in data set we need also to use proper libraries.

library(tidyverse)
library(readxl)
library(gmp)# for very big numbers
library(data.table)

input = read_excel(“Semi Prime Numbers.xlsx”, range = “A1:A10”)
test = read_excel(“Semi Prime Numbers.xlsx”, range = “C1:C5”)

Approach 1: Tidyverse with purrr

is_semiprime = function(n){
factors <- n %>%
as.character() %>%
as.bigz() %>%
factorize() %>%
as.vector()
check = ifelse(length(factors) == 2, TRUE, FALSE)

return(check)
}

result = input$Numbers %>%
keep(~ is_semiprime(.))

Approach 2: Base R

As function is_semiprime would only change form from piping to writing deep in parentheses, I will only adapt second part, calling function for two other approaches:

semiprimes_base <- unlist(lapply(input$Numbers, is_semiprime))
result_base <- input$Numbers[semiprimes_base]

Approach 3: Data.table

dt <- data.table(Numbers = input$Numbers)
dt[, IsSemiprime := sapply(Numbers, is_semiprime)]
result_dt <- dt[IsSemiprime == TRUE, .(Number)]

Validation

identical(result, test$`Expected Answers`)
[1] TRUE
identical(result_base, test$`Expected Answers`)
[1] TRUE
identical(result_base, test$`Expected Answers`)
[1] TRUE

Do not hesitate to show your approaches in R or even Python. Comment, share and come back for next puzzles.

--

--

Numbers around us
Numbers around us

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