The Factorial Function
The factorial function is a mathematical function that takes a non-negative integer n and returns the product of all positive integers less than or equal to n. The factorial function is denoted by n!.
This is a reference page for the factorial function, written in C and Python.
Background
The first 10 factorials are:
| n | n! |
|---|---|
| 0 | 1 |
| 1 | 1 |
| 2 | 2 |
| 3 | 6 |
| 4 | 24 |
| 5 | 120 |
| 6 | 720 |
| 7 | 5040 |
| 8 | 40320 |
| 9 | 362880 |
| 10 | 3628800 |
Where $n!=n\times(n-1)\times(n-2)\times\cdots\times2\times1$ and $n! = n\times(n-1)!$.
The Wikipedia page has a more detailed explanation of the factorial function.
Code
Psuedocode
This is the psuedocode for the factorial function:
FUNCTION factorial(n)
IF n = 0
RETURN 1
ELSE
RETURN n * factorial(n-1)
END IF
END FUNCTION
Factorial in C
This is a sample factorial function that gets the user’s input and returns the factorial of the input, written in C.
|
|
{: file="Factorial.c” }
|
|
{: file="Factorial.c Input and Output” }
The recursive factorial function could be simplified to a single line of code:
|
|
{: file="Factorial With Ternary Operator” }
This returns 1 if n is 0, otherwise it recursively returns n multiplied by the factorial of n-1.
I really like the use and elegance of Ternary Operators in C.
Factorial in Python
This is the same factorial function written in Python.
|
|
{: file="Factorial.py” }
|
|
{: file="Factorial.py Input and Output” }
|
|
{: file="Factorial.py” }
Similar to the C Version, the Python version could be simplified to a single line of code.