R Program to find the factorial of a number using recursion

How to find the factorial of a number using recursion

The factorial of a number is the product of all the integers from 1 to the number. Factorial is defined for positive integers only, we are not finding factorial for negative numbers. There is a formula defined for factorial for a given number n as,

n! =n x (n-1) x (n-2) x ... x 2 x 1

For example, the factorial of 5 is denoted as 5 ! which can be calculated as follows,

5 x 4 x 3 x 2 x 1  = 120

We have implemented a simple factorial program without recursion in our R program collection. We recommend you to check this program for a basic idea about factorial in detail.

Note: Factorial value of number zero is one ie., 0 ! =1

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 and calculate the product by multiplying the return value of each recursive function call.

We call a function factorial(5) to find the value of 5 !, the function returns a value like 5 x factorial(5-1) ie., inside the factorial function it again called the same function with next number 4. this will continue till returns a 1 with factorial(0). Finally, the product of each return value will give an answer 120.

Below given a detailed picture with the example of 5 ! Hope this will surely help you to catch the idea of recursive function easily.

How To Find Factorial Of A Number Using Recursion in R

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, a function is defined as recur_factorial() to calculate the factorial. From the main section, we call the recursive function by giving the number directly to the recur_factorial().

In the function check if the given number is less than or equal to 1, if yes return the value 1 because 0 ! and 1 ! gives the value one itself. If the condition is not true then call the function recur_factorial() again(ie., recursively) with argument num-1 and also multiply the return value with num to compute the product of all integers up to that number.

ALGORITHM

STEP 1: Call function recur_factorial()

STEP 2: Pass the number whose factorial needs to be found as num to function.

STEP 3: Check if the given number is greater than 1 or not, if yes do step 4 otherwise step5

STEP 4: return the value of num multiplied to the factorial of (num – 1 )

STEP 5: return 1 ie., num reaches to <= 1

R Source Code

                                          recur_factorial <- function(num) {
if(num <= 1) {
return(1)
} else { 
return(num * recur_factorial(num-1))
}
}

print(paste("The factorial of 5 is",recur_factorial(5)))

                                      

OUTPUT

[1] "The factorial of 5 is 120"