Suppose you're asked to write a recursive function in R that calculates the factorial of a number. How would you do it?

  • factorial <- function(n) { if (n <= 1) { return(1) } else { return(n * factorial(n - 1)) } }
  • factorial <- function(n) { if (n <= 1) { return(n) } else { return(n + factorial(n - 1)) } }
  • factorial <- function(n) { if (n <= 1) { return(0) } else { return(n * factorial(n)) } }
  • All of the above
To write a recursive function in R that calculates the factorial of a number, you can use the following code: factorial <- function(n) { if (n <= 1) { return(1) } else { return(n * factorial(n - 1)) } }. The function checks if the input n is less than or equal to 1. If it is, it returns 1 (base case). Otherwise, it multiplies n with the factorial of n - 1 (recursive case). This recursive calculation continues until the base case is reached.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *