The factorial of n
can be defined as the product of numbers from n
till 1
.
factorial()
function and we will pass the number we want to calculate the factorial for.#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) }
recur_fact
0!=1 && 1!=1
, so any factorial less than equal to 1
, we return the value 1
.n * recur_fact(n-1)
recur_fact()
with 8
as a parameter.factorial
function.fact
, with value one as we are performing without recursion.0!=1
situation.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
CONTRIBUTOR
View all Courses