Open In App

Calculate Factorial of a value in R Programming – factorial() Function

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
It is defined as:

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

For example



Factorials have important applications in mathematics, combinatorics, and probability theory.

Method 1: Using Factorial() Function

R Programming Language offers a factorial() a function that can compute the factorial of a number without writing the whole code for computing factorial.



Syntax: factorial(x)

Parameters:x: The number whose factorial has to be computed.

Returns: The factorial of the desired number.

Example 1




# R program to calculate factorial value
     
# Using factorial() method
answer1 <- factorial(4)
answer2 <- factorial(-3)
answer3 <- factorial(0)
 
print(answer1)
print(answer2)
print(answer3)

Output:

24

NaN

1

Example 2

Compute the factorial of multiple values




# R program to calculate factorial value
     
# Using factorial() method
answer1 <- factorial(c(0, 1, 2, 3, 4))
 
print(answer1)

Output:

1  1  2  6 24

Method 2: Finding Factorial Value Using If Else condition

We can create a program to find the factorial of a given number using R if-else conditions.

Steps:




# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative or possitive
if(num < 0) {
  print("Not possible for negative numbers")
} else if(num == 0) {
  print("The factorial of 0 is 1")
} else {
  for(i in 1:num) {
    factorial = factorial * i
  }
  print(paste("The factorial of", num ,"is",factorial))
}

Output:

[1] "The factorial of 6 is 720"

Article Tags :