Table of Contents
What's a Factorial?
The factorial of a positive integer n is the product of all positive integers less than or equal to n.
The factorial of a positive number n is given by n!(read as n factorial) where,
For example, The factorial of 4 is equal to 1 * 2 * 3 * 4 = 24
Also, factorials do not exist for negative numbers and the factorial of 0 is 1.
Using simple IterationIn this method, we just use a for loop and iterate n times and multiply all the numbers from 1 to n. Where n is the number we want to find the factorial for.
In the above program, an error message is shown when the user enters a negative number. When the user enters 0, the factorial is 1 and for a positive integer, a for loop is used to iterate from 1 to the number entered and all the numbers are multiplied to find the factorial with the product being stored in the fact variable after each iteration.
Using a recursive functionIn this method, we use the concept of the recursive function. Where a recursive function is a function that calls itself during its execution. These functions usually solve the same problem using fewer lines of code.
In the below example, we make use of the following formula where,
n! = n*(n-1)!
If you look at it closely and expand the (n-1)! it is the same as what we have discussed at the beginning of this article.