简体   繁体   中英

How to get the factorial using rep statement in r?

I want to get the factorial function with rep statement.

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:

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.

If you're into functional programming you could use the following lambda-based solution:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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