0

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. :)

1 Answers1

0

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]
snaut
  • 2,261
  • 18
  • 37