R Program to find the factorial of a number using a recursion

How to find the factorial of a number using a recursion

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

How factorial calculation is implemented in R Program

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.

ALGORITHM

  • STEP 1 : Call function recur_factorial()
  • STEP 2 : Pass the number whose factorial needs to be found as num.
  • STEP 3 : check if the given number is greater than 1
  • STEP 4 : if yes num is multiplied to the factorial of (num – 1 )
  • STEP 5 : Continue until the num reaches 1

R Source Code

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