【发布时间】:2019-08-29 08:50:05
【问题描述】:
我正在尝试从代码战中解决一个在 R 中称为阶乘分解的 kata。kata 的目的是分解 n! (阶乘 n) 转化为其质因数。该函数应该返回一个类似
的字符串decomp(12) -> "2^10 * 3^5 * 5^2 * 7 * 11"
我能够解决它,但达到了服务器超时(通过 74 次分配)。我尝试对其进行一些优化(pointwise() 的 lapply),但我无法更改基本核心(for-while-loop)。
任何帮助都将不胜感激,因为我投入的时间已经超出了我应有的时间。
##' 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"
【问题讨论】:
-
仅供参考
decomp(1000)在我的笔记本电脑上立即运行,decomp(10000)用时不到 2 秒。你知道是什么数量级让它超时吗? -
谢谢。与其他katas 有大约100-120 测试。我通过了 65-75 次测试。服务器时间最长 12 秒。
-
你知道是什么
n让它超时还是被隐藏了? -
至少对我来说它是隐藏的。这是kata的链接:codewars.com/kata/5a045fee46d843effa000070
-
您可能可以通过相反的方式提高性能:循环 2 和 n 之间的素数并计算出它们在阶乘中有多少个因数。不过,您必须处理多重性。
标签: r performance factorial