Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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

  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 0! is defined to be 1.

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




# 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




# 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:

  • readline(prompt=”Enter a number: “) reads a line of text from the user and displays the prompt “Enter a number: “.
  • as.integer() is used to convert the user’s input to an integer and store it in the variable num.
  • The initial factorial is initialized to 1.
  • if-else structure to check the value of num
    • If num is less than 0 (negative), it prints “Not possible for negative numbers.”
    • If num is equal to 0, it prints “The factorial of 0 is 1.”
    • If num is positive (greater than 0), it enters the else block to calculate the factorial.
      • Inside the else block, there is a for loop that iterates from 1 to num.
      • In each iteration, the factorial is updated by multiplying it by the current value of i. This loop calculates the factorial of the positive number.
      • After the loop completes, it prints the result using print() and paste() functions, displaying the calculated factorial along with a message.

R




# 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"


Last Updated : 25 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads