我寫了這個功能找到數階乘記憶化中的R
fact <- function(n) {
if (n < 0){
cat ("Sorry, factorial does not exist for negative numbers", "\n")
} else if (n == 0){
cat ("The factorial of 0 is 1", "\n")
} else {
results = 1
for (i in 1:n){
results = results * i
}
cat(paste("The factorial of", n ,"is", results, "\n"))
}
}
現在我想要實現的memoization在R.我有R上的基本理念,並試圖用它們來實現的階乘。但我不確定這是前進的方向。你能不能也請詳細說明這個話題。預先感謝。 Memoized階乘所有的
fact_tbl <- c(0, 1, rep(NA, 100))
fact_mem <- function(n){
stopifnot(n > 0)
if(!is.na(fib_tbl[n])){
fib_tbl[n]
} else {
fact_tbl[n-1] <<- fac_mem(n-1) * n
}
}
print (fact_mem(4))
這個包可能是有用的https://github.com/hadley/memoise –