Factorial and Recusion (04/08/2021)
The factorial of a number is the product of all the natural numbers less than the number. For example 1! = 1, 2! = 1×2 = 2, 3! = 1×2×3, and so forth. Factorials can be used to count the number of permutations of a collection of objects. For example, permutations of three numbers 123 include {123, 132, 213, 231, 312, 321}. Notice that 3! = 6 (the number of permutations of the three).
The following is a video on 0! by Numberphile.
So, how can we program a computer to calculate factorials? There are of course many ways, but my favourite has to be the recursive method; Notice that n! = n×(n-1)!. Turns out that this is all we need.
Here is a quick implementation in python:
code {
def factorial(n):
if n==0 return 1
else return n*factorial(n-1)
}
There are a few practical problems with the way I have implemented it. Firstly, it doesn't check if the input is an integer; if whoever's using the function used a number like a half as an argument to the function, it would never reach the base case and will loop indefinitely. A similar thing will happen for negative inputs.
Comments
Post a Comment