Factorial and Recursion
Now that we have conditionals, we can start to put together more sophisticated programs than we’ve seen so far. Let’s write a function to compute factorials. Factorials multiply all the numbers down to 1. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1
. But there’s a different way to define factorials that also works.
-
The factorial of 0 is 1.
-
The factorial of
x
isx
times the factorial ofx - 1
NOTE We’re ignoring negative numbers and non-integers.
In fact, we can write exactly that code in Rust. If you’re brave, try writing a function called fact
(short for factorial) that uses an if
/else
and calls itself. If you’re not brave, or when you want to check your answer, I’ve included a solution below.
Get hands-on with 1400+ tech skills courses.