Send
Close Add comments:
(status displays here)
Got it! This site "creationpie.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website. Note: This appears on each machine/browser from which this site is accessed.
Factorial function
1. Factorial function
The factorial function can be used to calculate the number of permutations of
n objects. The mathematical definition is as follows, using "
*" for multiplication.
fact(0) = 1
fact(n) = n * fact(n-1) , n > 0
Do you see a way to program the factorial function (top-down) using this definition?
Note that this definition is recursive in that it refers to itself.
The factorial function grows quickly.
n! = n * (n-1) * (n-2) * ... * 1
0! = 1
1! = 1
2! = 2 * 1 = 2
3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24
5! = 5 * 4 * 3 * 2 * 1 = 120
6! = 6 * 5 * 4 * 3 * 2 * 1 = 720
7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5,040
...
10! is more than 3,600,000
Do you see a way to program the factorial function bottom-up using the above pattern?
The factorial function grows rapidly. Here is a graphical depiction of
7! = 5,040.
59! is about 1080
1080is the number of baryons (electrons, protons, neutrons, etc.) in the known universe.
2. Main program
The main program code is the same for both versions of the code.
3. Iterative function
Here is an iterative factorial function (bottom up version).
It is called "iterative" because it has a loop. Pure recursive functions use recursion instead of loops, using recursion to do iteration.
4. Program
Here is the C code [#3]
5. Output
Here is the output of the C code.
6. Recursive function
Here is the recursive factorial function.
Here is the math definition, using "
*" for multiplication.
fact(0) = 1
fact(n) = n * fact(n-1) , n ≠ 0
7. Recursive function
Here is the same recursive factorial function written slightly differently.
The return is done at the end of the function.
8. Recursive function
Here is the same program using a recursive function (the first one).
Here is the C code [#6]
9. Output
Here is the output of the C code.
10. Tail recursion
Technical note: Tail recursion in the recursive version makes it easy to convert to iteration.
This improvement can be used in functional language, logic languages, and imperative languages.
This saves time and space since it avoids extra push and pops of the stack.
11. Redundant calculations
Problem: Redundant calculations are done.
Solution: Use memoization (behind the scenes) by trading more memory space for less computation time.
Memoization is from the Latin word "
memorandum" which comes from the Greek «
μνεμονικόυς» from the
PIE (Proto Indo-European) for "
men" or "
think" (comment, amnesia, mental, memento, etc.).
Memoization is often done for compiled regular expressions, SQL queries, etc. Space can be traded for time by using the hash of the text and not the text itself.
The browser cache is a form of memoization.
12. End of page