Dear Bob,
As I am sure you know, the factorial of any positive whole number is that number multiplied by all the numbers between it and 1.
So the factorial of 3 = 1 x 2 x 3 = 6
And the factorial of 5 = 1 x 2 x 3 x 4 x 5 = 120
I am also sure that, as a computer programmer, you could quickly write a program to calculate the factorial of any number N. One way to do it would be to set up a counter to cycle through all the numbers between 1 and N, multiplying each by a running total that is initially set to 1. In an imaginary programming language it might look like this:
RunningTotal = 1
FOR Counter = 1 to N
Multiply RunningTotal by Counter; (thereby altering the value of RunningTotal)
The factorial of N = RunningTotal
So, in calculating the factorial of 5, each step of the cycle would produce the following values:
Counter | Multiplication of RunningTotal x Counter |
New Value of RunningTotal |
1 | 1 x 1 | 1 |
2 | 1 x 2 | 2 |
3 | 2 x 3 | 6 |
4 | 6 x 4 | 24 |
5 | 24 x 5 | 120 |
But there is a more elegant way. This involves thinking of the factorial of any number N as being that number multiplied by the factorial of N-1.
So the factorial of 3 = 3 x 2 = 6
And the factorial of 5 = 5 x 24 = 120
And the factorial of 6 = 6 x 120 = 720
In our imaginary programming language, the program to calculate factorials using this method might look like this:
The factorial of 1 = 1
The factorial of N = N x the factorial of (N-1)
This is known as a recursive function because it has to re-use itself at each step of the calculation. For example:
The factorial of 5 = 5 x (the factorial of 4)
The factorial of 4 = 4 x (the factorial of 3)
The factorial of 3 = 3 x (the factorial of 2)
The factorial of 2 = 2 x (the factorial of 1)
The factorial of 1 = 1 (this causes the calculation to “unwind”)
So, the factorial of 2 = 2 x 1 = 2
So, the factorial of 3 = 3 x 2 = 6
So, the factorial of = 4 x 6 = 24
So, the factorial of 5 = 5 x 24 = 120
Isn’t that just exquisite!
Now, for homework, please would you explain the operation of recursive descent parsing giving examples from the Hebrew and Cherokee languages.
Sincerely yours