Related Tags

r
communitycreator
factorial

# Different ways of executing a factorial of a number using R()

### Overview

The factorial of n can be defined as the product of numbers from n till 1.

### Syntax

$n!=(1)* (2)* (3)* (4)* (5)*.....(n-1)*(n)$

#### Factorial with recursion

• The factorial function can be written as a recursive function call.
• Here, we pass the user input by calling the function.
• The function is called again and again until we encounter an exit condition.
• Whenever an action has to be performed repetitively, we often use the recursion.

#### Factorial without using recursion in R

• Here, we take input from the user, and using the loop constraint, we calculate the factorial.

#### Factorial with built-in function

• We call the factorial() function and we will pass the number we want to calculate the factorial for.

### Example

#method 1
#Recursive call
recur_fact <- function(n) {
if(n <= 1) {
return(1)
} else {
return(n * recur_fact(n-1))
}
}
recur_fact(8)
# method 2
# Built-in Factorail
num<-8
print(factorial(num))
#method 3
# Factorial without using built-in
fact <- 1
if (num < 0) {
print("Factorial for negative numbers not allowed!")
} else if (num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num){
fact=fact*i
}
print(fact)
}

### Explanation

• Line 3: We create a function recur_fact
• Lines 4–5: We then check for the value of n since 0!=1 && 1!=1, so any factorial less than equal to 1, we return the value 1.
• Lines 6–7 : We implement the logic of this code i.e n * recur_fact(n-1)
• Line 10 : We call the function recur_fact() with 8 as a parameter.
• Lines 13–14: We directly work with the built-in factorial function.
• Line 17: We define a variable, fact, with value one as we are performing without recursion.
• Line 18: As we don’t have factorial for negative numbers, we display the same.
• Lines 20–21: We write a condition to cater to the 0!=1 situation.
• Lines 22–27: We write a for loop with i as the loop variable. Then we move from 1 to n as i increases; we multiply it and store it in a variable fact.

RELATED TAGS

r
communitycreator
factorial

CONTRIBUTOR