Lesson goal: Computing the Factorial

Previous: The Fibonacci Sequence | Home | Next: Computing Pi using factorials

The factorial function is defined like this: The factorial of both $0$ and $1$ is $1$, and the factorial of numbers larger than $1$ are found like this:
  • The factorial of $2$ is $2\times 1=2$
  • The factorial of $3$ is $3\times 2\times 1=6$
  • The factorial of $4$ is $4\times 3\times 2\times 1=24$.
As for use, the factorial is written $n!$, where "the factorial of 3" would be written as $3!$, and you are meant to compute $3!$ by taking $3\times 2\times 1=6$. So the factorial of a number is found by multiplying the number by all of the integers smaller than it, stopping at $1$. The result means, in one example, the number of ways $n$ different objects can be arranged. For example, the three letters a, b, and c, can be arranged $3!=6$ different ways.

In this lesson, as more practice on how to write functions, we'll implement a factorial function. Remember, given a number $n$, the factorial is $n\times (n-1)\times (n-2)\times 1$. But if you look at a bit differently, you'll also see that $n!=1\times 2\times 3\times 4\times n$. This second definition is easiest to implement using a single for-loop. Use a for-loop to multiply the numbers from 1 to $n$ together.

See if you can complete the factorial function below. As for testing, be sure you get that fact(5)=120 and fact(10)=3628800. Note: We have an actual use for the factorial in a future lesson.

Now you try. Fix the for i=??? do line and the p=p* line to handle the factorial as described above.

Type your code here:

See your results here:

This code will not run! Fix the for loop. What will you have it count over? Next, fix the p=p * line to keep track of the rolling factorial product (p for "product"). Dismiss.
Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.