Here we are explaining how to write an R program to find the factorial of a number using a recursive function. Give the required number as an argument to the recursive function.
The factorial of a number is the product of all the integers from 1 to the number.
For example, the factorial of 5 (denoted as 6!) as
1 * 2 * 3 * 4 * 5 = 120
Given below are the steps which are used in the R program to find the factorial of a number using recursion. In this R program, we give the number directly to the function recur_factorial(). Check if the given number is greater than 1 if yes call the function recur_factorial() to compute the product upto that number.
recur_factorial <-
function(num) {
if(num <= 1) {
return(1)
} else {
return(num * recur_factorial(num-1))
}
}
recur_factorial(5)
## [1] 120
recur_factorial(10)
## [1] 3628800
recur_factorial(15)
## [1] 1.307674e+12
recur_factorial(20)
## [1] 2.432902e+18