I am trying to solve a kata from codewars called factorial decomposition in R. The aim of the kata is to decompose n! (factorial n) into its prime factors. The function should return a string like
decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"
I was able to solve it, but reached a server timeout (passing 74 assignments). I triet to optimize it a bit (lapply of pointwise()), but the essential core (for-while-loop) I was not able to alter.
Any help would be appreciated, as I put already more time into it than I should have.
##' A function for a factorial decomposition of a number
##' @title decomp
##' @param n integer
##' @return a String with the factorial decomposition
##' @author krisselack
decomp <- function(n) {
# https://stackoverflow.com/questions/19767408/prime-number-function-in-r
is.prime <- function(n) n == 2L || all(n %% 2L:ceiling(sqrt(n)) != 0)
p <- 2:n
primes <- p[as.logical(vapply(p, is.prime, 1))]
erg <- NULL
pointwise <- function(x) {
primloop <- primes[primes<=x]
for(j in primloop){
while(x %% j == 0){
x <- x/j
erg <- c(erg, j)
}
}
if(length(erg)>0)
return(erg)
}
erg2 <- unlist(lapply(p, pointwise))
ergfin <- table(erg2)
namen <- paste(ifelse(ergfin>1, paste0(names(ergfin), "^", ergfin),
paste(names(ergfin))),
collapse = " * ")
return(namen)
}
decomp(5) # -> "2^3 * 3 * 5"
decomp(12) # -> "2^10 * 3^5 * 5^2 * 7 * 11"
decomp(17) # -> "2^15 * 3^6 * 5^3 * 7^2 * 11 * 13 * 17"
decomp(25) # -> "2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23"