Factorial, the recursive way
No. 115
Q: |
Disclaimer: Calculating factorials using recursion is ways inefficient. However it allows for an easy demonstration of the underlying principle. This prepares for programming tasks where recursion is either the only known way or offers the most efficient implementation. Recursive programming is also a prerequisite for the later tic-tac-toe strategy exercise. Recursive programming uses methods calling themselves typically involving:
With respect to calculating factorials this may be expressed as:
This allows for calculating e.g.
Use the above scheme for implementing a second method
BTW: The concept of recursion in computer science is closely related to the mathematical concept of induction. |
|||||||||||||
A: |
The implementation is surprisingly simple:
If you fancy “compact” code you may even write:
Beware: The latter sacrifices both readability and the ability to debug for brevity. Your mileage may vary. |