Factorials
Learn how to recursively compute the factorial of integer n.
We'll cover the following
Recursive computation of factorials
This example is a slight cliché, but it is still a good illustration of both the beauty and pitfalls of recursion.
The factorial of an integer, , is the product of all the integers between and . For example, six factorial (usually written ) is:
Now, as we said in the introduction, the obvious way to do this is with a loop. But there is an alternative, “cleverer” way, using recursion.
We can make a simple observation that is actually . And is and so on. So, we can calculate without ever explicitly calculating a factorial at all. We just keep relying on smaller and smaller factorials without ever calculating them.
Of course, you must stop somewhere – we know that is .
Get hands-on with 1400+ tech skills courses.