|
14 | 14 | </p> |
15 | 15 |
|
16 | 16 | <p> |
17 | | - Let's take the familiar factorial function, which calculates <m>n!</m> (read as "n factorial"), so for example 5! = 5 × 4 × 3 × 2 × 1 = 120. Factorial is a classic example of recursion, where the function calls itself with a smaller value until it reaches a base case. |
18 | | - In general, <m>n! = n \times (n-1) \times (n-2) \times \cdots \times 2 \times 1</m>, |
19 | | - or recursively defined as <m>n! = n \times (n-1)!</m> with base cases <m>0! = 1</m> and <m>1! = 1</m>. |
| 17 | + Let's take the familiar factorial function, which calculates <m>n!</m> (read as "n factorial"), so for example <md> 5! = 5 × 4 × 3 × 2 × 1 = 120.</md> Factorial is a classic example of recursion, where the function calls itself with a smaller value until it reaches a base case. |
| 18 | + In general, <md>n! = n \times (n-1) \times (n-2) \times \cdots \times 2 \times 1</md>, |
| 19 | + or recursively defined as <md>n! = n \times (n-1)!</md> with base cases <m>0! = 1</m> and <m>1! = 1</m>. |
20 | 20 | </p> |
21 | 21 | <p> |
22 | 22 | You may recall mathematical notation using the symbol <m>\sum</m> (Greek letter sigma) |
23 | 23 | to represent "sum." For example, when we sum all elements in an array, we write |
24 | | - <m>\sum_{i=0}^{n-1} a_i</m>, where <m>i=0</m> below the symbol indicates we start at index 0, |
| 24 | + <md>\sum_{i=0}^{n-1} a_i</md>, where <m>i=0</m> below the symbol indicates we start at index 0, |
25 | 25 | <m>n-1</m> above it means we end at index <m>n-1</m>, and <m>a_i</m> represents the array |
26 | | - element at each index <m>i</m>. Similarly, <m>\sum_{i=1}^{n} i</m> means "sum all integers |
| 26 | + element at each index <m>i</m>. Similarly, <md>\sum_{i=1}^{n} i</md> means "sum all integers |
27 | 27 | <m>i</m> from 1 to <m>n</m>." |
28 | 28 | </p> |
29 | 29 | <p> |
30 | 30 | Factorial involves multiplication rather than addition, so we use the product symbol |
31 | | - <m>\prod</m> (Greek letter pi): <m>n! = \prod_{i=1}^{n} i</m>, which means "multiply |
| 31 | + <m>\prod</m> (Greek letter pi): <md>n! = \prod_{i=1}^{n} i</md>, which means "multiply |
32 | 32 | all integers <m>i</m> from 1 to <m>n</m>." Both summation and factorial can be expressed |
33 | 33 | recursively—summation as the first element plus the sum of remaining elements, and factorial |
34 | | - as <m>n \times (n-1)!</m>. |
| 34 | + as <md>n \times (n-1)!</md>. |
35 | 35 | </p> |
36 | 36 | <p> |
37 | 37 | Here is a Python implementation of factorial using just one function: |
|
0 commit comments