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
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 callrecur_fact <- function(n) {if(n <= 1) {return(1)} else {return(n * recur_fact(n-1))}}recur_fact(8)# method 2# Built-in Factorailnum<-8print(factorial(num))#method 3# Factorial without using built-infact <- 1if (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 to1, we return the value1. - 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()with8as a parameter. - Lines 13–14: We directly work with the built-in
factorialfunction. - 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!=1situation. - Lines 22–27: We write a
forloop withias the loop variable. Then we move from1tonasiincreases; we multiply it and store it in a variablefact.