R Examples

R Program - Find Factorial of a Number



The factorial of a positive integer is the multiplication of all positive integer less than or equal to that number.

factorial of number n = n! = n(n-1)(n-2)...1

For Example:

5! = 5 × 4 × 3 × 2 × 1 = 120

4! = 4 × 3 × 2 × 1 = 24

Method 1: Using Recursive method

In the example below, a recursive function called fact() is used to calculate factorial of a number.

fact <- function(x) {
  if (x == 0 || x ==1) {
    return (1)
  } else {
    return (x*fact(x-1))  
  }
}

cat("10! =", fact(10), "\n")
cat("6! =", fact(6), "\n")

The above code will give the following output:

10! = 3628800 
6! = 720 

Method 2: Using Iterative method

The factorial of a number can also be calculated using iterative method.

fact <- function(x) {
  final <- 1
  for (i in c(x:1)) {
    final <- final * i
  }
  return (final)
}

cat("10! =", fact(10), "\n")
cat("6! =", fact(6), "\n")

The above code will give the following output:

10! = 3628800 
6! = 720 

Method 3: Using in-built factorial function

To calculate the factorial of a number, the in-built R factorial() function can also be used.

cat("10! =", factorial(10), "\n")
cat("6! =", factorial(6), "\n")

The above code will give the following output:

10! = 3628800 
6! = 720