简体   繁体   English

如何在R中使用rep语句获取阶乘?

[英]How to get the factorial using rep statement in r?

I want to get the factorial function with rep statement. 我想用rep语句获取阶乘函数。

I try!! 我尝试! But failed!! 但是失败了!

   fact <- function(n){
      for (i in 0:n){
        while(i<n){
          rep{n*fact(n-1) if(i ==n) break}
       }
    }

thank you for your answer. 谢谢您的回答。 :) :)

Assuming you meant replicate , not rep this would be a solution: 假设您的意思是replicate而不是rep这将是一个解决方案:

fact <- function(N){
  n <- N
  f <- 1
  replicate(n, {
    f <<- f*n
    n <<- n-1
    f
  })[N]
}

Of course only use this as an exercise, because it is way slower than the build in factorial function. 当然,仅将其用作练习,因为它比factorial函数的构建要慢得多。

If you're into functional programming you could use the following lambda-based solution: 如果您从事函数式编程,则可以使用以下基于lambda的解决方案:

N <- 10

factorial_generator <- function(){
  fac <- 1
  n <- 0
  function(){
    n <<- n+1
    fac <<- fac * n
    return(fac)
  }
}

my_factorial <- factorial_generator()

replicate(N, my_factorial())[N]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM