R Program to find the factorial of a number using recursion

What is factorial? How to find it using recursion?

The factorial of a number is the product of all the integers from 1 to the number. it is defined for positive integers only, 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

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

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

How To Find Factorial Of A Number Using Recursion in R

How factorial calculation is implemented in R Program?

In this R program, a function is defined as recur_fact() to calculate the factorial. From the main section, we call the recursive function by giving the number directly to the recur_fact().

For example, We call a function fact(5) to find the value of 5 !, the function returns a value like 5 x fact(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 fact(0). Finally, the product of each return value will give an answer 120.

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_fact() 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_fact()

STEP 2: Pass the number 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


Please refer to the simple factorial program without recursion in our R program collection.

R Source Code

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

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

                                      

OUTPUT

[1] "The factorial of 5 is 120"